I have been practicing data structures with JavaScript recently and I found a snippet of code that I can't wrap my head around. I understand that when you assign an object to a variable, and then mutate the object, the original variable can "see" those mutations because when you assign the object to the variable you are not cloning the object, you are just passing a reference to it. However, the following code baffles my mind:
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
let tempList = [1, 1, 2, 4, 4, 100];
let point = new ListNode(tempList[0]);
let head = point;
for (let i = 1; i < tempList.length; i++) {
point.next = new ListNode(tempList[i])
point = point.next;
}
console.log(head); // Outputs the Linked List 1 -> 1 -> 2 -> 4 -> 4 -> 100
So when I try to follow the logic in my head, I picture it as follows:
In the first iteration, head and point hold the following information:
{
val: 1,
next: null
}
In the second iteration, point first holds this information:
{
val: 1,
next: {
val: 1,
next: null
}
}
and so does head, but then the next step is what is confusing me. In my head, I'm overriding the current value of point with the newly created Node in the step before, so the variable should look like this:
{
val: 1,
next: null
}
and head since it's just holding a reference from point should look like that as well. HOWEVER, head looks as follows:
{
val: 1,
next: {
val: 1,
next: null
}
}
and as the iterations keep going, obviously, head keeps track of all the linked nodes. That's the desired behavior, but I do not fully comprehend HOW that happens. Can somebody explain me why this is the case?
headsince it's just holding a reference frompointshould look like that as well" - no,headdoes not referencepoint. Afterhead = point, both variables do hold a reference to the object in memory. Not to each other.