python - 链表错误:'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吗?
解决方案
我认为您应该在 innit 部分中列出一个列表,因为您在 append 函数中所做的基本上是更新 head 变量,所以基本上它不是一个列表,因此您不能对该变量使用 next 方法
推荐阅读
- google-app-maker - 为什么 AppMaker 控制台未以预览模式显示?
- sql - 添加到 Group By 时出现无效的列名错误
- typescript - Vue & TypeScript 如何在渲染中获取数据属性?
- python - 这是我应该使用十进制库的情况吗?
- sorting - 如何在 Swi Prolog 上进行插入排序
- javascript - 我将如何根据计数增加进度条线?
- arrays - 检查数组中值的特定组合
- php - IF 语句失败
- python - Pandas groupby 计算百分比变化列
- c# - 使用 C# 和 Microsoft.TeamFoundationServer.Client 将代码签入到 TFS 2017