【发布时间】:2022-11-03 01:21:20
【问题描述】:
我正在尝试在 python 中学习链表。这是一个非常简单的代码。我在这里要做的就是调用一个类的构造函数。但这给了我一个错误。它在说:
#This is the code I have written please help me resolve this problem
class node:
def __init__(self,data):
self.data=data
self.next=None
class linkedlist:
def __init__(self,head):
self.head=None
def insertathead(self,data):
newnode=node(data)
if(self.head==None):
self.head=newnode
else:
newnode.next=self.head
self.head=newnode
def insertatend(self,data):
newnode=node(data)
if(self.head==None):
self.head=newnode
else:
temp=self.head
while(temp.next!=None):
temp=temp.next
temp.next=newnode
def insert(self,position,data):
newnode=node(data)
count=1
if(self.head==None):
self.head=newnode
elif(position==1):
newnode.next=self.head
self.head=newnode
else:
while(temp.next!=None):
if(count==position):
break
else:
prev=temp
temp=temp.next
count=count+1
prev.next=newnode
newnode.next=temp
def printlist(self):
if(self.head==None):
print("your list is empty")
else:
temp=self.head
while(temp.next!=None):
print(temp,end=' ')
temp=temp.next
mylist=linkedlist()
mylist.insertathead(25)
mylist.printlist
File "D:\roug1.py", line 51, in <module>
mylist=linkedlist()
TypeError: __init__() missing 1 required positional argument: 'head'
这是我的编译器给出的错误。我不知道该怎么做。谁能给我正确的代码
【问题讨论】:
标签: python data-structures linked-list singly-linked-list