Reputation: 33
My doubt is when I am making b=c.next,it means b will point to Node d. But when I start printing from the head node, it gives answer as 5,6,7,8. Why is my line b=c.next not executed. The answer must be 5,8 right?
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
a.next.next=c
a.next.next.next=d
b=c.next
print(a.data,b.data,c.data)
while a is not None:
print(a.data)
a=a.next
Upvotes: 0
Views: 55
Reputation: 134045
Your line b=c.next
is getting executed. If you were to write:
while b is not None:
print (b.data)
b=b.next
You would see the output 6 8
. It prints b.data
and then b.next.data
(which is the same as d.data
).
References don't work quite the way you think they do. When you create the initial nodes, you have essentially this (=>
here means "refers to"):
a => Node5
b => Node6
c => Node7
d => Node8
Those assignments create new nodes, and make the variables refer to those nodes. But a
,b
,c
, and d
are references to nodes, not the nodes themselves.
When you assign next
references:
Node5.next => Node6
Node6.next => Node7
Node7.next => Node8
You're changing what those nodes refer to.
Finally, you change b
, creating:
b => Node8
When you assign to b
, you're telling b
, "instead of referring to Node6
, start referring to Node8
." But Node5.next
is still referring to Node6
.
If you want to change the order so that it goes 5,8
, you'd have to write:
a.next = c.next
Another way to look at it is to create one node and two references, like this:
a = Node(5)
b = a
Now, obviously, a.data
and b.data
will both be 5. And if you write b.data = 6
, then a.data
will also be 6 because a
and b
are referring to the same thing.
But what happens if you then write b = Node(12)
? Now what you've done is created a new node and made b
refer to it. But a
is still referring to the node with value 6. So, a.data = 6
and b.data = 12
.
Changing what b
refers to doesn't change what a
refers to.
Upvotes: 2