Let's say we're trying to implement a linked list in Python, with each ListNode defined as following:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
And let's also say we have a simple linked list of 1 -> 2 -> 3 -> None, defined as following:
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
a.next = b
b.next = c
Now when I hold a variable pointing to c and update itself like this:
c = c.next
I expected that the linked list from a will look like: 1 -> 2 -> None because node c is updated. However, to my surprise, the linked list from a still keeps its original form: 1 -> 2 -> 3 -> None.
Why is this the case? Doesn't the variable c hold the actual reference to that ListNode object and the change to itself should therefore reflect when we see the entire list from node a?
Assignment to a name (variable) never mutates a data structure, like setting an attribute of an object.
Here is your linked list:
Once you assign
c = c.next, you're taking the value ofc.next-- which isNoneand assign it to thecname:When you'd want that
b.nextbecomesNone, you'll really have to assign that tob.next. Note thatb.nextis an attribute that is distinct from the namec.