简体   繁体   中英

Java Linked List "insertAfter" - method

public void insertAfter(String after, String newName, int newPunkte)
{
    ListNode newNode = new ListNode(newName, newPunkte, null);

    if(head == null)
    {
        System.out.println("'InsertAfter' is not possible.");
        return;
    }
    else
    {
        current = head;

        while(current != null)
        {
            if(current.getName().equals(after))
            {
                System.out.println(after+" was found. "+newName+" was created.");
                //Here is my problem...
                current.setNext(newNode);
                return;
            }
            previous = current;
            current = current.getNext();
        }
        System.out.println(after+" was not found.");
        return;

    }
}

Hey guys, Ive got a little problem with my code. When I insert a new Node after a (if so) found Node, the following Nodes (after the new one) are disappearing.. I pretty sure that the problem is that i didnt set "previous" after inserting. Im pretty inexperienced with implementing Linked Lists. I hope you can help me:)

By the way for understanding my code: The parameter "newPunkte" means "newPoints".

You need to set the next node on newNode:

ListNode next = current.getNext();
current.setNext(newNode);
newNode.setNext(next);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM