[英]Python error for Linked List append function
我正在尝试使用 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):
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
我的完整代码写在上面。 代码有什么问题?
它应该是
def __init__(self,data):
init 两边各有 2 个下划线
代码中的错误并不是说 Node() 没有接受任何参数,而是试图解释 Node() 在初始化时不应该接受任何参数。
我对 Node 本身了解不多,但是看看错误,这就是我的结论。
这是因为您在创建__init__
函数时犯了一个简单的语法错误。 _init_
周围有一个下划线,而它应该是带有 2 个下划线的__init__
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.