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

链表尾部添加元素遇AttributeError报错,求报错原因解析

链表尾部添加元素触发AttributeError的原因解析

问题场景

向链表尾部添加元素时,执行以下代码出现错误:AttributeError: 'NoneType' object has no attribute 'next'

错误代码片段:

def add_last(self, node_to_add):
    curr = self.head
    while curr is not None:
        curr = curr.next
    curr.next = Node(data = node_to_add)

改用curr.next作为循环判断条件时,添加操作能成功完成;同时之前用while curr is not None:的逻辑处理节点删除是有效的,想明确其中的差异和错误原因。

错误根源

你的循环逻辑while curr is not None:会持续遍历,直到curr变成None才终止——这时候curr已经走到了链表最后一个节点的后继空位置,而非最后一个节点本身。None是没有next属性的,所以执行curr.next = ...必然触发属性错误。

而删除节点时该逻辑有效,是因为删除操作的目标场景不同:比如删除指定值的节点时,遍历过程中是通过curr节点检查其next节点的内容,或者删除最后一个节点时,你的逻辑可能提前终止在倒数第二个节点,根本不会让curr走到None的位置,自然不会触发类似错误。

正确的尾部添加实现

要在链表尾部添加节点,需要遍历到最后一个有效节点(即curr.next为None的节点),而非遍历到空指针。正确代码如下:

def add_last(self, node_to_add):
    # 处理链表为空的边界情况
    if self.head is None:
        self.head = Node(data=node_to_add)
        return
    curr = self.head
    # 遍历到最后一个节点(curr.next 为空)
    while curr.next is not None:
        curr = curr.next
    # 将最后一个节点的next指向新节点
    curr.next = Node(data=node_to_add)

这样能保证curr始终是一个有效的链表节点,不会出现None调用next的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:36:06