问题
When I don't use the "insertBefore" method, it just prints out the linked list normally like it is supposed to. But when I try to use the insertBefore method, it does work for the first part but then it keeps printing the link list as if it goes on forever,
ex:
without insert before it prints out " my Tests::::
head ->3 -> 2 -> 1 -> 4 -> ||| "
But when I use insertBefore and print it out, it prints out
head ->3 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> 4 -> and it keeps on going and going forever
here is the insertBefore method
private boolean insertBefore(Node aNode, Node beforeNode)
{
Node currentNode;
Node prevNode;
//aNode= new Node();
currentNode = this.getHead();
while(currentNode!=null && currentNode.getNext()!=aNode)
{
if(currentNode == beforeNode)
{
prevNode = this.getPrevious(beforeNode);
prevNode.setNext(aNode);
aNode.setNext(beforeNode);
//aNode.setNext(currentNode);
return true;
}
currentNode = currentNode.getNext();
}
currentNode.setNext(beforeNode);
return false;
}
The insertBefore method does do its job, but then it makes the link list continue on forever, and i'm wondering why
回答1:
You need to add aNode.setNext(currentNode)
回答2:
You are manipulating what looks like a doubly linked list (since you have getPrevious)
Your current list is: 1 <-> 2 <-> 3 <-> 4
You want to add 'a' before 3:
I don't see all these updates here.. only PrevNode.setNext(aNode).
Note (This is not a Doubly linked list then you are only missing 1 set not 3 but then there is really no need to do a full second scan of the list twice just to find the previous node).
来源:https://stackoverflow.com/questions/20023562/linked-list-cant-figure-out-why-this-insert-before-method-is-causing-the-link