Python单链表look()函数报NoneType无next属性的AttributeError问题排查
单链表look()方法触发AttributeError问题排查
问题描述
我尝试创建一个简单的单链表,代码如下:
class node: def __init__(self, data=None): self.data = data self.next = None class linkedlist: def __init__(self): self.head = node() def append(self, data): curr = self.head new_node = node(data) while curr.next != None: curr = curr.next curr.next = new_node def total(self): curr = self.head total = 0 while curr.next != None: curr = curr.next total += 1 return total def display(self): # added total here as well curr = self.head em = [] total = 0 while curr.next != None: curr = curr.next em.append(curr.data) total += 1 print(f"LinkedList: {em} \n Total: {self.total()} ") def look(self, index): if index >= self.total(): print("ERROR: Index error" ) curr_index = self.head idx = 0 while True: curr_index = curr_index.next if idx == index: print(curr_index.data) idx += 1
调用look()函数时,出现如下错误:
curr_index = curr_index.next ^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'next'
我知道curr_index使用的是self.head,而self.head是node()实例,node类包含next属性。调用类中其他函数时无此错误,且这些函数能正常返回结果。我的代码哪里出错了?
问题原因及修复方案
核心问题
你的look()方法存在两个关键问题:
- 无限循环导致越界:
while True是无限循环,即便找到目标索引,循环仍会继续执行,直到curr_index走到链表最后一个节点的next(也就是None),此时再访问curr_index.next就会触发AttributeError。 - 错误处理不完整:当
index >= self.total()时,你只打印了错误提示,但没有终止函数,后续代码依然会运行,同样会导致越界访问。
修复后的look()方法
def look(self, index): # 补充负索引的判断,更严谨 if index >= self.total() or index < 0: print("ERROR: Index error") return # 打印错误后直接返回,终止后续代码执行 curr_index = self.head idx = 0 while curr_index.next is not None: curr_index = curr_index.next if idx == index: print(curr_index.data) return # 找到目标节点后立即返回,结束循环 idx += 1
额外优化建议
- 遵循Python命名规范:类名采用大驼峰格式,将
node改为Node,linkedlist改为LinkedList,提升代码可读性。 look()方法可以改为返回节点数据而非直接打印,让方法的复用性更强。total()方法可以简化,不需要移动指针到链表末尾,直接计数即可(当前实现也能正常工作)。
内容的提问来源于stack exchange,提问作者Epimu Salon
相关产品推荐
相关产品推荐

