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

Why do I have an error saying that "self" is not defined?

I am creating a linked list where I insert at the beginning of the list but i keep on getting that "NewNode" in NewNode.nextval = self.headval and "self" in self.headval = NewNode is undefined

Here is my code:

# creation of linked list
class Node:
    def __init_(self, dataval=None):
        self.dataval = dataval
        self.nextval = None
        
class linked_list:
    def __init__(self):
        self.headval = None
# Print linked list        
    def listprint(self):
        printval = self.headval
        while printval is not None:
            print(printval.dataval)
            printval = printval.nextval
    def AtStart(self,newdata):
       NewNode = Node(newdata)
# for updating new nodes next val to existing node
    
    NewNode.nextval = self.headval
    self.headval = NewNode
    
list = linked_list()
list.headval = Node("2")
e2 = Node("3")
e3 = Node("4")
list.headval.nextval = e2
e2.nextval = e3
list.AtStart("1")
list.listprint()

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 :

Well you have a few problems.

  1. You are missing an underscore in the init method of Node change it to def __init__
  2. There are a few lines which probably should be part of AtStart but aren’t because of indentation

Change

def AtStart(self,newdata):
   NewNode = Node(newdata)
# for updating new nodes next val to existing node
    
NewNode.nextval = self.headval
self.headval = NewNode

to

def AtStart(self, newdata):
    NewNode = Node(newdata)

    # for updating new nodes next val to existing node
    NewNode.nextval = self.headval
    self.headval = NewNode
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