首页 > 解决方案 > 链表错误:'int' 对象没有属性 'next'

问题描述

我刚刚开始使用这里的数据结构。我正在尝试用 python 实现链表。但是一直报错!我将非常感谢您的洞察力。这是我的代码,

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


class LinkedList(object):
    def __init__(self):
        self.head = Node()

    def append(self, new_element):
        current = self.head
        if self.head:
            while current.next:             #line 14
                current = current.next
            current.next = new_element
        else:
            self.head = new_element

    def length(self):
        count = 0
        current = self.head
        if self.head:
            while current.next:
                count += count
                current = current.next
            return count
        else:
            return count

    def display(self):
        elements = []
        current = self.head
        if self.head:
            while current.next:
                elements.append(current)
                current = current.next
            print(elements)
        else:
            print(elements)


my_list = LinkedList()
my_list.append(1)
my_list.append(2) #line 45
my_list.append(3)
my_list.append(4)
my_list.append(5)
my_list.length()
my_list.display()

这是错误消息:

Traceback (most recent call last):
  File "C:/Users/Desktop/ds/linkedlist.py", line 45, in <module>
    my_list.append(2)
  File "C:/Users/Desktop/ds/linkedlist.py", line 14, in append
    while current.next is not None:
AttributeError: 'int' object has no attribute 'next'

我的所有方法都有相同的错误,即在LinkedList类中追加、长度和显示。错误说current是int吗?

标签: pythonpython-3.xlinked-list

解决方案


我认为您应该在 innit 部分中列出一个列表,因为您在 append 函数中所做的基本上是更新 head 变量,所以基本上它不是一个列表,因此您不能对该变量使用 next 方法


推荐阅读