0

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.

1 Answer 1

2

Remember, javascript passes objects by reference. resultHead.next = head means modifying resultHead.next modifies head externally. You set slow and fast to resultHead so modifying slow.next modifies head.

i.e.

slow === resultHead
resultHead.next === head
slow.next === head
Sign up to request clarification or add additional context in comments.

1 Comment

Okay so what happens in the while loop when I set slow=slow.next. Doesn't it set the slow variable to point to a different object(the next node in the list)? After the loop ends it will end at node.val=3, now does the slow takes the node reference inside the resultHead?

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.