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

链表删除倒数第N个节点代码报错AttributeError: 'NoneType' object has no attribute 'next'的修复求助

链表删除倒数第N个节点代码报错AttributeError: 'NoneType' object has no attribute 'next'的修复求助

Hey there! Let's break down why your code is hitting that AttributeError and fix it up properly.

First, let's look at the core issues in your original code:

  • You didn't handle the edge case where you need to delete the head node (when the node to remove is the first one in the list). For example, if the list has exactly n nodes, m = cnt - n will be 0, and your current code tries to access temp.next where temp might be None (like when the list only has 1 node).
  • Your logic for traversing to the target node uses redundant variables (temp and curr) which leads to accessing next on a None value when the list is short.

Fixed Version of Your Original Approach

Here's the corrected code that addresses these issues, with clear explanations:

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        # Step 1: Calculate the total length of the linked list
        temp = head
        cnt = 0
        while temp:
            temp = temp.next
            cnt += 1
        
        m = cnt - n
        # Edge case: We need to delete the head node directly
        if m == 0:
            return head.next
        
        # Step 2: Traverse to the node right before the one we want to delete
        curr = head
        # Move curr m-1 times to reach the predecessor of the target node
        for _ in range(m - 1):
            curr = curr.next
        
        # Step 3: Skip the target node by updating the next pointer
        curr.next = curr.next.next
        return head

Key Fixes:

  1. Handled head node deletion: When m = 0, we directly return head.next instead of trying to modify pointers (since there's no node before the head to adjust).
  2. Simplified traversal: We only track curr to reach the node right before the target, eliminating the redundant temp variable that could become None and cause errors.

Bonus: More Efficient Two-Pointer Approach

If you want a more optimal solution (only one pass through the list instead of two), you can use the slow-fast pointer technique with a dummy node (to avoid messy edge case handling for the head):

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        # Dummy node acts as a predecessor to the head, simplifying edge cases
        dummy = ListNode(0, head)
        slow = dummy
        fast = head
        
        # Move fast pointer n steps ahead first
        for _ in range(n):
            fast = fast.next
        
        # Move both pointers until fast reaches the end of the list
        while fast:
            slow = slow.next
            fast = fast.next
        
        # Now slow points to the node before the one we need to delete
        slow.next = slow.next.next
        return dummy.next

This approach runs in O(n) time with O(1) space, and avoids the need to calculate the list length upfront.

备注:内容来源于stack exchange,提问作者Farjana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 12:15:26