开发者社区> 问答> 正文

链表追加功能的Python错误

我正在尝试学习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

我的完整代码写在上面。代码有什么问题?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 14:22:04 738 0
2 条回答
写回答
取消 提交回答
  • 这个 init 貌似写错了啊

    2020-03-24 14:23:30
    赞同 展开评论 打赏
  • 它应该是

    def __init__(self,data):
    

    init的每一侧都有2个下划线

    回答来源:stackoverflow

    2020-03-24 14:22:11
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载