【问题标题】:I was trying linkedlist program in python and got the error ""'Node' object has no attribute 'next"". '我在 python 中尝试链表程序并得到错误“”'Node'对象没有属性'next“”。 '
【发布时间】:2021-04-22 16:12:36
【问题描述】:
class Node:
    def __init__(self,data = None, Next = None):
        self.data = data
        self.Next = Next

class LinkedList:
    def __init__(self):
        self.head = None
    def insertAtBegining(self,data):
        node = Node(data,self.head)
        self.head = node
    def Print(self):
        if self.head == None:
            print("Empty Linkelist")
        itr = self.head
        lstr = ''
        while itr:
            lstr += str(itr.data) + '-->'
            itr = itr.next
        print (lstr)
        
if __name__ == '__main__':
    obj1 = LinkedList()
    obj1.insertAtBegining(5)
    obj1.insertAtBegining(10)
    obj1.insertAtBegining(15)
    obj1.Print()

我在 Node 类中遇到错误,说它没有 next 属性。

【问题讨论】:

    标签: python python-3.x linked-list


    【解决方案1】:

    它没有next,它有Next,它们是不同的,您可以将itr.next 更改为itr.Next,或者(更好,与您的命名一致)更改您的Node对此的定义:

    class Node:
        def __init__(self, data = None, next = None):
            self.data = data
            self.next = next
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2022-01-24
      • 2017-08-03
      • 2022-01-14
      • 1970-01-01
      • 2016-03-06
      相关资源
      最近更新 更多