移除链表倒数第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
相关产品推荐
相关产品推荐

