[英]Inserting into the sorted linked list
我在这行得到nullpointerexception
:
while(data > current.data)
我有一个按升序排序的有序列表,即insertInPos()
将节点插入适当的位置。 但是为什么我会得到nullpointer
?
public void insertInPos(int data){
if(head == null){
head = new Node(data, null);
}
else if(head.data > data){
Node newNode = new Node(data, null);
newNode.next = head;
head = newNode;
}
else{
Node newNode = new Node(data, null);
Node current = head;
Node previous = null;
while(data > current.data){
previous = current;
current = current.next;
}
previous.next = newNode;
newNode.next = current;
}
}
主班
public class Tester {
public static void main(String[] args){
LinkedList myList = new LinkedList();
myList.insertInPos(1);
myList.insertInPos(2);//Getting nullpointer from here
myList.insertInPos(3);
myList.insertInPos(4);
myList.insertInPos(7);
myList.insertInPos(7);
myList.insertInPos(8);
System.out.println();
myList.displayList();
}
}
您收到错误消息是因为在列表末尾, current
变为null
。
将您的条件更改为关注
while(current != null && data > current.data){
previous = current;
current = current.next;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.