public void addNode(Car newCarEntry){
ListNode currentNode;
ListNode newNode = new ListNode(newCarEntry);
if (head == null || newCarEntry.isNewerThan(head.carItem)){
newNode.next = head;
head = newNode;
}else{
currentNode = head.next;
while(currentNode != null && !newCarEntry.isNewerThan(currentNode.carItem) ){
currentNode = currentNode.next;
}
currentNode.next = newNod开发者_开发技巧e.next;
currentNode = newNode;
}
numberOfNodes++;
}
This looks a lot like homework, so I'm not going to be putting any code in here, but in your else statement you are finding the insertion point for the new node, and setting the new node's next to point to the remainder of the list, but you are not actually putting your new node in the list at any point.
Assume you have a one-node list [HEAD]->null
. Now the following lines will be executed:
currentNode = head.next; // => null
while(currentNode.next != null && !newCarEntry.isNewerThan(currentNode.carItem) ){
...
}
Thus it will give you a null pointer exception (accessing currentNode.next
) when you try to add the second node.
After the Edit: Now the null pointer exception will not come up any more. Instead the following happens:
currentNode = head.next; // => null
while(currentNode != null && ...) { // => not entering loop
...
}
newNode.next = currentNode; // => i.e. null
newNode = currentNode; // => i.e. null
You are only changing the local variable newNode
but not the list or the head at all.
精彩评论