Mike
Mike

Reputation: 75

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.

Upvotes: 0

Views: 3721

Answers (2)

Durai Kasinathan
Durai Kasinathan

Reputation: 71

Change your for loop as below

for(i = 0; i < input; i++ ) {
    people = scnr.next();
    numberOfpeople=scnr.nextInt();
    currNode = new PeopleNode(people, numberOfpeople);
    lastNode.insertAtFront(headNode, currNode);
    lastNode = currNode;
}

Upvotes: 0

Daniel Williams
Daniel Williams

Reputation: 665

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 ...

Upvotes: 1

Related Questions