1

I'm learning about linked lists right now. I found an example for java that places a new node into the 3rd position on a linked list, but I've only ever seen insertion into a certain spot in the middle of a list like this done using 2 additional nodes, current and previous. I've also never seen anything like .getNext after another one like this. So can someone explain what each part of this snippet of code does and maybe rephrase it using nodes current and previous so I can understand how it relates and compares? Elem is the name given to the node being inserted and you don't have to instantiate current and previous if you do add an explanation involving those. I'll just assume it's already done.

elem.setNext(first.getNext().getNext());
first.getNext().setNext(elem);
numberOfElems++; 

Please let me know if you need more info to answer!

1 Answer 1

2
elem.setNext(first.getNext().getNext());

As you said, elem is the element being inserted. The line of code above sets elem's next reference to the third element of the list (first.getNext().getNext() references the third element).

first.getNext().setNext(elem);

The second line of code sets the second element's next reference to the new element being inserted. The new element is now inserted in between the old second and third elements, making it the third element in the list.

The last line of code just increments the count of elements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.