我有一个通用的有序链表类。出于某种原因,每次运行 add() 时都会重新分配 LinearNode 头。有任何想法吗?为什么每次运行时都会改变头部?我什至没有碰它。如果需要,我可以提供其他类进行测试。
public class myOrLiList<T extends Comparable<T>> {
public LinearNode head;
public int count;
public myOrLiList() {
head = null;
count = 0;
}
// LinearNode INNER CLASS
public class LinearNode {
public LinearNode next;
public T item;
public LinearNode(T thisitem) {
this.next = null;
this.item = thisitem;
}
}
public boolean isEmpty() {
return (head == null);
}
public void add(T thisItem) {
LinearNode newNode = new LinearNode(thisItem);
if (isEmpty()) {
head = newNode;
System.out.println("head filled!");
} else {
LinearNode compareNode = head;
do {
if (thisItem.compareTo(compareNode.item) < 0) {
newNode.next = compareNode;
break;
} else if ((thisItem.compareTo(compareNode.item) < 0)
|| (thisItem.compareTo(compareNode.item) == 0)) {
newNode.next = compareNode.next;
compareNode.next = newNode;
break;
} else {
compareNode = compareNode.next;
}
} while (compareNode.next != null);
}
System.out.println("Added!");
count++;
}
谢谢你的帮助。