I need some pointer on how does memory in Javascript works. In my implementation of removing the n-th node from the tail of a linked list I have a place holder resultHead.
At the end of the code I have console log the resultHead and the first time is just the original assignment of head:
{"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":4,"next":{"val":5,"next":null}}}}}
But the second time after I have this line:
slow.next = slow.next.next
Then the console logs out:
{"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":5,"next":null}}}}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
if(head.next === null){return null}
// use resultHead as a place holder and its next is the actual head
let resultHead = new ListNode(null);
resultHead.next = head;
// find the difference between fast and slow pointer
let fast = resultHead;
let slow = resultHead;
for(let i=0; i<=n; i++){
fast=fast.next;
}
while(fast){
slow = slow.next
fast = fast.next
}
console.log(JSON.stringify(resultHead.next))
slow.next = slow.next.next
console.log(JSON.stringify(resultHead.next))
return resultHead.next;
};
removeNthFromEnd({"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":4,"next":{"val":5,"next":null}}}}}, 2)
So the code should remove the node with node.val = 4
How can the slow.next = slow.next.next changed the value of resultHead?
I also tried to console log the resultHead in different places but only after the slow.next = slow.next.next changed the value of resultHead.