问题
public void addNode(Car newCarEntry){
ListNode currentNode;
ListNode previousNode;
ListNode newNode = new ListNode(newCarEntry);
if (head == null || newCarEntry.isNewerThan(head.carItem)){
newNode.next = head;
head = newNode;
}else{
currentNode = head.next;
previousNode = head;
while(currentNode != null && !newCarEntry.isNewerThan(currentNode.carItem)){
currentNode = currentNode.next;
previousNode = currentNode;
}
newNode.next = currentNode;
newNode = previousNode.next;
}
}
回答1:
You have a mistake in the way you advance the pointers. Change:
currentNode = currentNode.next;
previousNode = currentNode;
to
previousNode = currentNode;
currentNode = currentNode.next;
Your way you make both currentNode and previousNode holding references to the same object, which is not what you want.
EDIT: Also your last line should be
previousNode.next = newNode;
insead
newNode = previousNode.next;
because you are not attaching the new node to the list this way.
来源:https://stackoverflow.com/questions/6558511/in-this-linked-list-method-i-try-to-add-a-item-in-sorted-order-but-i-am-getting