我正在尝试将项目插入到自定义链接列表中,同时保持列表有序。
到目前为止我的工作是这样的:
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;
}
}
}
我从中得到的输出看起来像是对列表的部分内容进行了排序,然后重新开始。
示例(我正在对字符串进行排序):
而不是得到类似a,b,c,...,z
我得到a,b,c,...,z,a,b,c,...,z,a,b,c,...,z
所以看起来它在某些时候没有“看到”整个列表。
这是硬件作业的一部分,所以我很感激建议,但让我尝试自己解决它!
最佳答案
如果插入的元素大于所有现有元素,会发生什么情况?
您想在末尾插入该元素,但实际上您是在开头插入它。任何后面的元素都将插入在此之前(如果它们较小),或者在开始时再次插入。
关于java - 按顺序将项目插入自定义链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6713736/