I am really confused by the Python linked list data structure used in Leetcode. I am not sure if the problem is caused by the specific ListNode structure created by Leetcode, or I have some misunderstanding about Python. For example, the following piece of code is simple and self-explained:
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def main():
# Instantiate a linked list 1 -> 2 -> 3
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
a.next = b
b.next = c
print(a) # a is 1 -> 2 -> 3
b.next = None
print(a) # a is 1 -> 2
b = None
print(a) # a is still 1 -> 2, why changing b doesn't change a, but changing b.next changes a???
Suppose I have a linked list a -> b -> c. When I set b.next = None, a.next.next = None. However, the thing that confuses me is that, when I set b = None, a.next doesn't become None.What's the difference between operating b and b.next, why they have different influence on a?
ListNodeclass whose instances can be used to build a linked list, but no class that encapsulates the idea of a linked list and provides methods likeappend,insert,find,remove, etc.ListNodestructure? I just don't understand why changingbandb.nexthas different influenceabhas no effect on other references to the same object.a.next = bis "makea.nextpoint at the same thingbis pointing at currently", and then the second bindingb = Noneshould be read as "make b point to nothing now". Read this way, it makes it a bit more clear that the second binding has no influence ona.next.