Linked list - Can't figure out why this insert before method is causing the link list to expand

非 Y 不嫁゛ 提交于 2019-12-13 04:26:15

问题


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:

  • so you need to find Node 2 & 3
  • update 2.Next to a, and a.Previous to 2
  • update a.Next to 3 and 3.Previous to a

    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

  • 易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!