I came across this answer on LeetCode for the “Remove Nth Node From End of List” Linked List Problem. https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/524116/JavaScript-One-Pass-Two-Pointer
I understand why I need to update curr.next
to curr.next.next
. But I don’t understand how this change modifies the head
too. I thought curr
was just a variable.
How does changing curr
changes the head
too?
Advertisement
Answer
I don’t understand how this change modifies the head too. I thought
curr
was just a variable.
If this assignment were an assignment to curr
you’d be right, and it wouldn’t mutate the list, but the assignment is not to curr
, but to curr.next
, and that is not a variable, but an attribute of a node in your list. By assigning to that attribute, you effectively mutate that node, and by consequence the list.