Java 按顺序将项目插入自定义LinkedList
我试图将项目插入到自定义链接列表中,同时保持列表的有序性 我目前的工作是:Java 按顺序将项目插入自定义LinkedList,java,sorting,insert,linked-list,Java,Sorting,Insert,Linked List,我试图将项目插入到自定义链接列表中,同时保持列表的有序性 我目前的工作是: public class CustomList { public CustomList() { this.first = null; } public void insert(Comparable newThing) { Node point = this.first; Node follow = null; while (p
public class CustomList {
public CustomList() {
this.first = null;
}
public void insert(Comparable newThing) {
Node point = this.first;
Node follow = null;
while (point != null && point.data.compareTo(newThing) < 0) {
follow = point;
point = point.next;
}
if (point == null) {
Node newNode = new Node(newThing);
newNode.next = this.first;
this.first = newNode;
} else {
Node newNode = new Node(newThing);
newNode.next = point;
if (follow == null) {
this.first = newNode;
} else {
follow.next = newNode;
}
}
}
private Node first;
private class Node {
public Comparable data;
public Node next;
public Node(Comparable item) {
this.data = item;
this.next = null;
}
}
}
公共类自定义列表{
公共客户列表(){
this.first=null;
}
公共无效插入(可比纽廷){
节点点=this.first;
Node follow=null;
while(point!=null&&point.data.compareTo(newThing)<0){
跟随=点;
point=point.next;
}
如果(点==null){
Node newNode=新节点(newThing);
newNode.next=this.first;
this.first=newNode;
}否则{
Node newNode=新节点(newThing);
newNode.next=点;
if(follow==null){
this.first=newNode;
}否则{
follow.next=newNode;
}
}
}
私有节点优先;
私有类节点{
公共可比数据;
公共节点下一步;
公共节点(可比项){
这个数据=项目;
this.next=null;
}
}
}
我从中得到的输出看起来像是对列表的一部分排序,然后重新开始
示例(我正在对字符串排序):
而不是像a,b,c,…,z那样
我得到a,b,c,…,z,a,b,c,…,z,a,b,c,…,z
因此,在某些点上,它似乎没有“看到”整个列表
这是HW作业的一部分,所以我很感激你的建议,但让我自己试着弄清楚 如果插入一个大于所有现有元素的元素,会发生什么情况
您希望在末尾插入元素,但实际上是在开头插入。然后,任何后续元素都会在此之前插入(如果它们较小),或者在开始时再次插入。虽然看起来很像家庭作业,但我要给你一个小提示:你确定在point==null
时总是将节点放在列表的开头是可以的吗?是的,它是硬件的一部分(我真的忘了写,但现在已经修复了). 根据您的建议,我认为既然point==null也可能发生在列表的末尾,那么我应该包括它吗?您可以从Node point=this开始简化它
而不是节点点=this.first代码>。然后,您只在列表的末尾得到point==null
。“是的,你的假设是对的。”穆瑟,我不确定我是否明白。因为“this”是我的自定义LL,所以它只会引用自身,并给出一个错误。我想指向第一个节点(除了.next外,它是空的)。哦,对不起,你肯定是对的:)只要把这种特殊情况处理一下,当first=null
放在列表的开头,而在所有其他情况下,当point==null
时,你应该在列表的末尾。如果不是if(point==null),该怎么办{我使用了:(point==null&&follow==null){Node newNode=newNode(newThing);newNode.next=this.first;this.first=newNode;}如果(point==null){Node newNode=newNode(newThing);newNode.next==null;point.next==newNode;看起来更好…试试看。(我无法在评论中真正阅读您的代码。如果仍然不起作用,请更新问题中的代码(有一个编辑链接),并描述您现在得到的内容。)