Home > database >  How to add elements in custom linked list
How to add elements in custom linked list

Time:01-10

    class Node:
        def __init__(self,data=None):
             self.data=data
             self.next=None
    class Linked:
        def __init__(self):
             self.head=None

        def show(self):
             node=self.head()
             while node is not None:
                 print(node.data)
                 node=node.next

    listt=Linked()
    element=Node("4")
    listt.head=(element)
    element2=Node("5")
    listt.head.next=element2
    listt.show()

Error:

TypeError: 'Node' object is not callable

Please tell me what is wrong here. I understood the error but where should I make the changes to add an element to the list?

CodePudding user response:

head is declared as variable, so self.head() is a wrong call.

class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None


class Linked:
    def __init__(self):
        self.head = None

    def show(self):
        node = self.head
        while node is not None:
            print(node.data)
            node = node.next


listt = Linked()
element = Node("4")
listt.head = element
element2 = Node("5")
listt.head.next = element2
listt.show()

Output:

4
5
  •  Tags:  
  • Related