我在这行中得到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;
}