Home > Software design >  Why does the linked list pointer inside Python list become separate?
Why does the linked list pointer inside Python list become separate?

Time:03-16

After saving a pointer to a linked list node in a variable 'head', I inserted the 'head' inside a Python list (named 'tail'). Then, even if I traversed the linked list by accessing the 'head' variable in the Python list, I can still access the head of the linked list by accessing 'head'. One can check by comparing the two ids : id(head) != id(tail[0]).

Why is it so?

head = ListNode(0)          # Stored a pointer to a ListNode(0)
tail = [head]               # Assigned a pointer to a Python list having a 'head' as an element
tail[0].next = ListNode(1)  # Attached a ListNode(1)
tail[0] = tail[0].next      # Traversed
id(head) == id(tail[0])     # Gives 'False'; two ids are unequal.

# FYI - ListNode definition
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

CodePudding user response:

tail[0].next = ListNode(1)  # Attached a ListNode(1)
tail[0] = tail[0].next      # Traversed

in terms of what happens to the array is just

tail[0] = ListNode(1)

And then you are somehow confused why that is not equal to head?! Because head is still ListNode(0).

What is True is id(head.next) == id(tail[0]).

  • Related