链表错误:'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类中的append、length和display。错误是说current是int吗?

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

您正在将int元素(而不是Nodes(追加到列表中,因为您的append方法是为Nodes(作为next_element(设计的,但您正在传递ints。

相反,请执行以下操作:

my_list.append(Node(1))

最好按以下方式调整append方法,这样就可以添加任意元素,而无需手动创建Nodes

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

要不是显示Nodes(它们是对象,所以你可以看到内存位置(,而是显示它们的值,你必须在display方法中调整一行:

elements.append(current.data)

最新更新