Teddy13
Teddy13

Reputation: 3854

Linked List insert after

I am a student just learning Java. I have a big test tomorrow and I am a confused by a certain line of code.

The method, insertAfter, finds the number in the linkedList passed into the method and inserts a new node after the match. I do not understand how

 curr.setNext(curr.getNext()) 

will take us to the next Node in the list that potentially could be the number we are looking for. So how does this command iterate us through the linked list?

Does it not make more sense to go curr=curr.getNext()?

Thanks and sorry if this is very simple... I am very confused at the moment

// assume firstInList is in the list
public void insertAfter(int firstInList, Node toAdd){
    Node curr = head;

    while( curr.getData() != firstInList ){
        curr.setNext(curr.getNext());
    }

    curr.setNext(toAdd);        
}


   Node class
  {
   int getData() {return data};
   void setData(int data) {this.data =data};
   Node getNext() {return next};
   void setNext(Node next) {this.next = next};
  }

}

Additional Method The method is called

   public void insertBefoe (Node, inList, Node toAdd)

Upvotes: 1

Views: 3487

Answers (2)

NPE
NPE

Reputation: 500187

It seems pretty clear that the code should read:

curr = curr.getNext()

instead of

curr.setNext(curr.getNext());

Additionally, the following is broken:

curr.setNext(toAdd);        

Once this has been executed, the part of the list that follows firstInList will be lost.

Upvotes: 1

Shervin Asgari
Shervin Asgari

Reputation: 24499

The code doesn't look correct.

Where is head coming from? Looks like it will never come out of the while loop, unless the setNext(..) somehow also alters the code in getData()

Unfortuantly its difficult to help since we don't have the whole picture

Upvotes: 0

Related Questions