LeetCode反转链表问题:NoneType属性错误排查求助
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 returnsNoneright away, skipping the invalidcur.nextaccess entirely. - The second approach initializes
prevasNone, and iterates only as long ascurexists. For empty lists,curstarts asNone, the loop never runs, and we returnprev(which isNone)—exactly the correct result. For non-empty lists, we gradually reverse pointers by updatingcur.nextto point topreveach 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

