链表删除倒数第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
nnodes,m = cnt - nwill be 0, and your current code tries to accesstemp.nextwheretempmight beNone(like when the list only has 1 node). - Your logic for traversing to the target node uses redundant variables (
tempandcurr) which leads to accessingnexton aNonevalue 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:
- Handled head node deletion: When
m = 0, we directly returnhead.nextinstead of trying to modify pointers (since there's no node before the head to adjust). - Simplified traversal: We only track
currto reach the node right before the target, eliminating the redundanttempvariable that could becomeNoneand 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
相关产品推荐
相关产品推荐

