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

移除链表倒数第N个节点时出现'NoneType' object has no attribute 'next'错误

问题分析与修复

错误触发场景

当你要删除的是链表的头节点时,比如:

  • 链表只有单个节点 [1],n=1
  • 链表是 [1,2],n=2
    这两种情况都会触发NoneType' object has no attribute 'next'错误。

错误原因

当删除头节点时,你的代码中b最终会等于head。进入while a.next != b循环时:

  • 初始a=head,如果链表只有一个节点,a.next是None,循环条件None != head成立,执行a = a.next,此时a变成None
  • 下一次循环判断a.next时,自然就会抛出属性不存在的错误
  • 就算链表长度大于2,只要b是头节点,循环也会一直执行到a变成None,最终触发同样的错误

修复后的代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        a = head
        b = head
        c = head

        i = 0
        while i < n - 1:
            c = c.next
            i += 1

        while c.next is not None:
            b = b.next
            c = c.next
        
        # 特殊处理删除头节点的情况
        if b == head:
            return head.next
        
        while a.next != b:
            a = a.next
            
        a.next = b.next
        b = None
    
        return head

额外优化建议

你用的是快慢指针的思路,可以用哑节点(dummy node)来避免处理头节点的特殊情况,让代码逻辑更统一:

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        slow = dummy
        fast = head
        
        # 让fast先走n步
        for _ in range(n):
            fast = fast.next
        
        # 快慢指针一起走,直到fast到末尾
        while fast:
            slow = slow.next
            fast = fast.next
        
        # 删除slow的下一个节点
        slow.next = slow.next.next
        return dummy.next

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:55:20