Linked List Swap Node - node.next value changes for no reason, why?

Hey everyone!

So I’m working through Pass the Technical Interview with JavaScript course. It’s all going well but I like to work through the code more thoroughly to make sure I am truly understanding it.

The issue: Swapping Elements in a Linked List

In this article, there is a strange change happening that I can not follow… it all WORKS in the end but I need help understanding WHY

The Code - GitHub

It is difficult to explain but I will try.

We are trying to swap 2 nodes in a linked list, node1, and node2. We look for data1 and data2 in the list and then switch the position of these two nodes, obviously by changing their pointers.

Let’s say that I have a testList from 1 - 10.

I want to swap 6 and 5 using the swapNodes(testList, 6, 5) function.

I follow the changes through the function with console.log so I can confirm my predictions.

The problem is that the node2.next.data value is changed and I can’t figure out why.

Follow what happens first:

  1. node2Prev = 4 - makes sense
  2. node2 = 5 - correct
  3. node2.next.data = 6 - also correct

I can follow this as the 4, 5, 6 are the logical values for node2.

Next:

  1. node1Prev.next is assigned to node2 (which is 5)
  2. node2.next.data is now 5 - WHY!?!

This is the problem, why does node2.next.data become 5? It was 6 a just a few lines ago and nowhere in between was it changed by the code…

Ultimate Question:

Can anyone explain to me why node.next.data is changed to 5 seemingly at random? When, in my opinion, it should be 6.

Thanks so much, appreciate your time.

Mory
The Code - GitHub

The github link isn’t working…

Have you tried drawing it out on paper alongside a summary in pseudo-code? Personally this helps me with data structures, but it doesn’t work with everyone.

Hey thanks for the reply,

Sorry the Code link should be working now…

I did right it out on paper, and it still doesn’t make sense why it changes…

Try putting tracers at every juncture. I know you put some in, but maybe even more detailed ones that track how data changes and are formatted in an easy way

console.log (this is node 1 in the first while loop: ${node1.data});

this is node 1 in the first while loop: 0
this is node 1 in the first while loop: 1
this is node 1 in the first while loop: 2
this is node 1 in the first while loop: 3
this is node 1 in the first while loop: 4
this is node 1 in the first while loop: 5