I am having trouble with the following code segment. I can’t really figure out why it doesn’t work, any help is appreciated. It’s a very very simple mistake that I do not understand:
JavaScript
x
15
15
1
class Node():
2
def __init__(self, val = 0, next_node = None):
3
self.val = val
4
self.next = next_node
5
6
def add_node(self, new_val):
7
temp = self
8
self.val = new_val
9
self.next = temp
10
11
if __name__ == '__main__':
12
u = Node(1)
13
u.add_node(5)
14
print(u.next.val)
15
Prints 5 and it keeps printing 5 if you write u.next.next.next.val
, what I want is u.val = 5
, u.next.val = 1
and u.next.next = None
Advertisement
Answer
You’d have to instantiate a new Node
in add_node
, and then set it as next
of self
.