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

LeetCode反转链表问题:NoneType属性错误排查求助

Fixing the AttributeError in Your Reverse Linked List Code

Hey there! Let's break down why you're hitting that AttributeError and how to fix it.

The Root Cause

Your error pops up when the input linked list is empty (i.e., head is None). When you set cur = head, cur becomes None immediately, and trying to access cur.next throws the error because NoneType doesn't have a next attribute. Your current code doesn't handle this edge case at all.

The Fix

We can adjust the code to handle empty lists first, or refactor the iteration logic to be more robust. Here's a revised version that covers all cases, including empty lists and single-node lists:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # Handle empty list case first to avoid invalid attribute access
        if not head:
            return None
        
        cur = head
        nxt = cur.next
        while nxt != None:
            temp = nxt.next
            nxt.next = cur
            cur = nxt
            nxt = temp
        
        head.next = None
        head = cur
        return head

Or, an even cleaner iterative approach that naturally handles empty lists without an explicit check:

class Solution(object):
    def reverseList(self, head):
        prev = None
        cur = head
        while cur:
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
        return prev

Why This Works

  • The first fix adds a simple check for not head (empty list) and returns None right away, skipping the invalid cur.next access entirely.
  • The second approach initializes prev as None, and iterates only as long as cur exists. For empty lists, cur starts as None, the loop never runs, and we return prev (which is None)—exactly the correct result. For non-empty lists, we gradually reverse pointers by updating cur.next to point to prev each iteration.

Additional Testing Tips

Make sure to test these edge cases to confirm your code works:

  • Empty list (head = None)
  • Single-node list (only one element, no next node)
  • Multi-node list (your original logic works here once the empty case is handled)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:35:27