NeverGiveUp
NeverGiveUp

Reputation: 33

Linked List ques

My doubt is when I make A.next=None, Shouldnt kam variable also store None? Why is still pointing to Node 6?

class Node:

  def __init__(self, data):   # data -> value stored in node
      self.data = data
      self.next = None



a=Node(5)
b=Node(6)
c=Node(7)
d=Node(8)
a.next=b 
b.next=c 
c.next=d 
kam=a.next
a.next=None


while kam is not None:
    print(kam.data)
    kam=kam.next

Upvotes: 1

Views: 58

Answers (3)

Shivangi Singh
Shivangi Singh

Reputation: 1139

No kam is pointing to b. And when you do A.next = None the next pointer of A points to none but kam holds reference to b. Think of them to be exclusive.

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

My doubt is when I make A.next=None, Shouldnt kam variable also store None? Why is still pointing to Node 6?

No. Python performs assignments. It thus sets kam to reference to what a.next is referencing at that moment. It thus copies the reference. If you later alter that value, that will not reflect on the kam itself, since it made a copy of the reference at the moment you assigned it.

So kam is referring to b since of the moment of assignment, a.next was referring to b:

kam=a.next    # kam = b
a.next=None   # a.next = None

Upvotes: 0

Rafael
Rafael

Reputation: 7242

That's because you make next attribute of a instance None, not c node. When Python runs kam=a.next what really happens is that kam becomes whatever a.next value is pointing at. If you later change a.next then it's not implied that kam will change.

Upvotes: 1

Related Questions