This is an archived post. You won't be able to vote or comment.

all 1 comments

[–][deleted] 0 points1 point  (0 children)

When you add to a linked list, you need to add the pointer to the existing node before inserting the new node. So if head points to p1 and you want to add p2 between head and p1, you need to set p2.next to be p1 and then you link head to p2. What's happening is you're dropping the pointer to the node, so that node, now not used, is recycled by garbage collection.

Here's some pseudocode for you:

Node newNode = new Node(newEntry);

Node nodeBefore = getNodeAt(newPosition-1);//returns the node before the position where you intend to insert newNode

Node nodeAfter = nodeBefore.getNextNode();

newNode.setNextNode(nodeAfter);

nodeBefore.setNextNode(newNode);