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()
>Solution :
Well you have a few problems.
- You are missing an underscore in the init method of Node change it to
def __init__ - There are a few lines which probably should be part of
AtStartbut 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