Python使用单链表实现队列触发AttributeError问题咨询
单链表实现队列的bug修复方案
报错根因
你触发的AttributeError: 'NoneType' object has no attribute 'link'来自enqueue方法的逻辑漏洞:
当队列为空(self.front is None)时,你已经将self.front赋值为新节点,但变量p保存的是赋值前的self.front(也就是None),代码没有跳出当前方法,继续执行while p.link判断时就会访问None的属性触发报错。
其他存在的问题
- 类初始化只定义了
self.front头指针,但size()、display()方法中错误调用了不存在的self.start属性 display()方法逻辑错误:循环遍历到指针为None才停止,之后打印指针内容必然触发属性错误,正确逻辑是遍历过程中打印当前节点值dequeue()方法没有做空队列校验,空队列调用时也会触发属性报错- 入队逻辑的空队列分支没有跳过后续尾插逻辑,会导致第一个节点的link指向自己,形成环
修复后的完整代码
class Node: def __init__(self, value): self.info = value self.link = None class Queue: def __init__(self): self.front = None def enqueue(self, data): temp = Node(data) # 空队列直接赋值头节点后返回,不执行后续尾插逻辑 if self.front is None: self.front = temp return # 非空队列遍历找尾节点 p = self.front while p.link is not None: p = p.link p.link = temp def dequeue(self): # 空队列直接返回避免报错 if self.front is None: print("队列已空,无法出队") return self.front = self.front.link def size(self): # 替换不存在的self.start为self.front p = self.front n = 0 while p is not None: n += 1 p = p.link return n def display(self): print("\n当前队列元素:", end="") p = self.front # 遍历过程中打印节点值 while p is not None: print(p.info, '', end='') p = p.link qu = Queue() for i in range(4): add = int(input("please enter the elements ")) qu.enqueue(add) qu.display() for i in range(2): qu.dequeue() qu.display()
内容的提问来源于stack exchange,提问作者Mahzad
相关产品推荐
相关产品推荐

