Skip to content
Advertisement

Wrong Implementation of LinkedList

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:

class Node():
    def __init__(self, val = 0, next_node = None):
        self.val = val
        self.next = next_node

    def add_node(self, new_val):
        temp = self
        self.val = new_val
        self.next = temp

if __name__ == '__main__':
    u = Node(1)
    u.add_node(5)
    print(u.next.val)

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement