链表附加函数的Python错误
我正在尝试学习使用python3实现链表。调用append函数时,我的代码抛出错误“TypeError:Node()不带参数”链表附加函数的Python错误,python,python-3.x,linked-list,jupyter,Python,Python 3.x,Linked List,Jupyter,我正在尝试学习使用python3实现链表。调用append函数时,我的代码抛出错误“TypeError:Node()不带参数” class Node: def _init_(self,data): self.data=data self.next=None class LinkedList: def _init_(self): self.head=None def print_list(self): cu
class Node:
def _init_(self,data):
self.data=data
self.next=None
class LinkedList:
def _init_(self):
self.head=None
def print_list(self):
cur_node=self.head
while cur_node:
print(cur_node.data)
cur_node=cur_node.next
def append(self,data):
new_node=Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node=last_node.next
last_node.next=new_node
llist = LinkedList()
llist.append('A')
llist.append('B')
上面代码的错误是
TypeError Traceback (most recent call last)
<ipython-input-4-893f725212cd> in <module>
1 llist = LinkedList()
----> 2 llist.append('A')
3 llist.append('B')
<ipython-input-3-a7f4eb6e69c9> in append(self, data)
14
15 def append(self,data):
---> 16 new_node=Node(data)
17 if self.head is None:
18 self.head = new_node
TypeError: Node() takes no arguments
TypeError回溯(最近一次调用)
在里面
1 llist=LinkedList()
---->2.allist.append('A')
3.allist.append('B')
附加中(自身、数据)
14
15 def附加(自身、数据):
--->16新节点=节点(数据)
17如果self.head为无:
18 self.head=新节点
TypeError:节点()不接受任何参数
我的完整代码写在上面。代码有什么问题吗?应该是
def __init__(self,data):
代码中的错误不是说Node()没有接受任何参数,而是试图解释Node()在初始化时不应该接受任何参数 我对节点本身了解不多,但看看错误,这就是我的结论
这是因为在执行
\uuuu init\uuuu
函数时出现了一个简单的语法错误。您在\u init\u
周围有一个下划线,而它应该是\u init\u
,带有两个下划线。它应该是\u init\u(self,data)谢谢…您是正确的。你的建议解决了问题。@sayakchowdhury那么你能把它标记为正确答案吗?