You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python链表代码运行报错AttributeError: 'NoneType'无data属性求解

报错原因与修复方案

报错原因

问题出在LL类的print_LL方法里的循环判断条件:

while self.head is not None:

self.head是链表的头节点,只要链表不为空,它就永远不会是None,这会导致循环无限执行。当遍历到最后一个节点时,node = node.ref会把node变成None,此时再执行print(node.data),就会触发AttributeError: 'NoneType' object has no attribute 'data'。

修复方法

把循环条件改成判断当前遍历的node是否为None,这样遍历到链表末尾时循环会自动终止。修改后的print_LL方法如下:

def print_LL(self):
    if self.head is None:
        print("LL is empty")
    else:
        node = self.head
        while node is not None:
            print(node.data)
            node = node.ref

完整修复后的代码

class Node:
    def __init__(self, data):
        self.data = data
        self.ref = None
        
class LL:
    def __init__(self):
        self.head = None
        
    def print_LL(self):
        if self.head is None:
            print("LL is empty")
        else:
            node = self.head
            while node is not None:
                print(node.data)
                node = node.ref
    
    def add_begin(self, data):
        new_node = Node(data)
        new_node.ref = self.head
        
        self.head = new_node
        
        
ll1 = LL()
ll1.add_begin(10)
ll1.add_begin(20)
ll1.print_LL()

运行后会输出:

20
10

内容的提问来源于stack exchange,提问作者Anonymous Stranger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:40:22