我刚刚创建了一个从头创建的链表,目前为止我创建了两个插入新元素到列表的方法。一种方法将元素放置在列表的开始位置,另一种方法将其放在列表的后面。我现在试图创建第三种方法,其中我试图放入列表中的元素将根据元素的值进行放置。所以如果我试图插入的元素的值小于列表中的第一个元素,但低于列表中的第二个元素,我希望该方法自动将新元素放置在这两个元素之间。当插入一个新元素时,从最低值到最高值对链表进行排序
这听起来很简单,但我现在意识到执行起来比我想象的要困难得多。我似乎无法停止NullPointerExceptions和其他错误,所以在这一点上我完全空白,不知道下一步该怎么做。
Anywas,下面的代码:
import java.util.*;
public class OrdnetLenkeliste<T extends Comparable<T>> extends Lenkeliste<T>{
public void insert(T element){
Node node = new Node(element);
if(super.isEmpty()){
node.next = head;
head = node;
numberOfNodes++;
} else {
Node currentNode = head;
Node previous = null;
while(currentNode != null){
if(currentNode.data.compareTo(node.data) < 0){
currentNode = currentNode.next;
} else if (currentNode.data.compareTo(node.data) > 0 && currentNode.previous.data.compareTo(node.data) < 0){
node = currentNode.previous;
currentNode.previous = node.previous;
currentNode = currentNode.next;
numberOfNodes++;
} else if(currrentNode.data.compareTo(node.data) == 0){
currentNode = currentNode.next;
currentNode.previous = node;
numberOfNodes++;
}
}
}
}
}
有可能是在变量的几个拼写错误,但这只是因为我翻译的变量名,使代码更易读。
欢迎来到Stack Overflow!请参考[游览](http://stackoverflow.com/tour),环顾四周,阅读[帮助中心](http://stackoverflow.com/help),特别是[我该如何问一个好问题?](http://stackoverflow.com/help/how-to-ask)和[我可以问什么问题?](http://stackoverflow.com/help/on-topic)。 - 请始终添加*完整*错误消息,并指出代码示例中的哪些行与此错误消息中的行号相对应。 –