Search code examples
javaarrayslinked-listnodes

Unable to insert node at the front of linked list


I am trying to create a program that uses insertAtFront() to insert at the front of linked list. The first user input defines the number of nodes, followed by elements for each node (age and name). I think I am messing up the insertAtFront() method in the second class, but I don't know what I'm doing wrong exactly.


Solution

  • You pass the headNode into insertAtFront, but it is never used. I believe it should be

    public void insertAtFront(PeopleNode headNode, PeopleNode currNode) {
        currNode.nextNodeRef = headNode.nextNodeRef;    
        headNode.nextNodeRef = currNode;
    }
    

    Here is a visual of what is happening. It starts like this:

    head -> person1 -> person2 -> person3 ...

    First we make the new node point to the node that head is already pointing to:

    head -> person1 -> person2 -> person3 ...
              ^
           currNode
    

    Then we make the head point to the current node:

    head -> currNode -> person1 -> person2 -> person3 ...