Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add elements in custom linked list

    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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading