Python链表运行报错AttributeError: 'LinkedList' object has no attribute 'head'求助
问题修复说明
你遇到的报错及代码存在3处可修复的问题,具体如下:
- 第一个问题(报错直接诱因):
LinkedList类的构造方法拼写错误。你当前写的是def __int__(self),但Python类的构造方法固定为__init__(前后双下划线,中间是init缩写)。拼写错误导致实例化链表时构造方法没有执行,self.head属性从未被定义,就触发了对应AttributeError。 - 第二个问题:
printList方法中节点游标移动逻辑缩进错误。你当前把currentNode = currentNode.next写在了while循环外部,循环内游标永远不会移动,会陷入死循环重复打印第一个节点的内容,需要把这行代码缩进放到while循环内部。 - 第三个问题:第三个节点插入操作不完整。你写的
linkedlist.insert没有加括号传入第三个节点对象,不会实际执行插入逻辑,需要改为linkedlist.insert(thridNode)。
修正后完整代码
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList(): # 修正构造方法拼写 def __init__(self): self.head = None def insert(self, newNode): if self.head is None: self.head = newNode else: lastNode = self.head while True: if lastNode.next is None: break lastNode = lastNode.next lastNode.next = newNode def printList(self): currentNode = self.head while True: if currentNode is None: break print(currentNode.data) # 修正缩进,把游标移动放到循环内 currentNode = currentNode.next firstNode = Node('john') linkedlist = LinkedList() linkedlist.insert(firstNode) secondNode = Node('Ben') linkedlist.insert(secondNode) thridNode = Node('Matthew') # 补全第三个节点的插入逻辑 linkedlist.insert(thridNode) linkedlist.printList()
运行修正后代码会输出如下结果:
john Ben Matthew
内容的提问来源于stack exchange,提问作者chris tchassem
相关产品推荐
相关产品推荐

