Reputation: 31
code:
class node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist:
def __init__(self):
self.head=None
def printlist(self):
temp=self.head
while(temp):
print(temp.data,end=" ")
temp=temp.next
def insert_at_start(self,new_data):
new_node=node(new_data)
if self.head==None:
new_node=self.head
else:
new_node.next=self.head
self.head=new_node
l1=linkedlist()
insert_at_start(1)
insert_at_start(5)
insert_at_start(1)
insert_at_start(7)
insert_at_start(5)
l1.printlist()
error: Traceback (most recent call last): File "linkedlist.py", line 65, in insert_at_start(1) TypeError: insert_at_start() missing 1 required positional argument: 'new_data'
Upvotes: 1
Views: 447
Reputation: 18315
First you have the indentation problem that those 2 functions (printlist
and insert_at_start
) should be methods, so indent them to lie in the linkedlist
class. Also two more errors: one is, you need the call
l1.insert_at_start(..)
i.e. the method call on the instance. And the other is a logical error that resides in the lines of:
if self.head == None:
new_node = self.head
When .head
does not exist yet, don't you think .head
should be the one assigned to the new_node
?
Also note that l1
is probably one of the most confusing variable names ever existed, please change it; and PascalCase your class names.
Upvotes: 1
Reputation: 9504
You have an indentation problem: insert_at_start
is not a method of linkedlist
class because it is defined outside of the class scope and that's why it requires 2 args.
Try this instead:
class linkedlist:
def __init__(self):
self.head=None
def printlist(self):
temp=self.head
while(temp):
print(temp.data,end=" ")
temp=temp.next
def insert_at_start(self,new_data):
new_node=node(new_data)
if self.head==None:
new_node=self.head
else:
new_node.next=self.head
self.head=new_node
l1=linkedlist()
l1.insert_at_start(1)
l1.insert_at_start(5)
l1.insert_at_start(1)
l1.insert_at_start(7)
l1.insert_at_start(5)
l1.printlist()
Upvotes: 1