K个一组翻转链表问题中TypeError: 'ListNode' object is not iterable错误的排查求助
Hey there! Let's break down why you're hitting that TypeError and how to fix it.
The Root Cause
The error happens because your reversesubList method doesn't consistently return two values, but you're trying to unpack its result into two variables (reversed_head, new_head = self.reversesubList(...)).
Look at this line in reversesubList:
if cur.next is None: return A
When this condition is true (e.g., when the sublist has only one node), the method returns a single ListNode instead of a tuple of two values. Python can't unpack a single object into two variables, hence the "not iterable" error.
This check is actually unnecessary anyway—your main while loop already handles all cases, including single-node sublists.
The Fix
Remove the redundant if cur.next is None check, and make sure reversesubList always returns a tuple of two values: the head of the reversed sublist, and the start of the next group (or None if we've reached the end). Also, the self.head = prev line is unused, so you can delete that too.
Here's the corrected reversesubList method:
def reversesubList(self, A, B): prev = None cur = A count = 0 while cur is not None and count < B: nxt = cur.next cur.next = prev prev = cur cur = nxt count += 1 # Always return reversed head and next group start return prev, cur
Full Corrected Solution
Putting it all together, your Solution class should look like this:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reversesubList(self, A, B): prev = None cur = A count = 0 while cur is not None and count < B: nxt = cur.next cur.next = prev prev = cur cur = nxt count += 1 return prev, cur def reverseList(self, A, B): current = A last_of_prev = None count = 0 start = None while current is not None: reversed_head, new_head = self.reversesubList(current, B) if count == 0: start = reversed_head else: last_of_prev.next = reversed_head last_of_prev = current current.next = new_head current = new_head count += 1 return start
Quick Logic Check
- For each group of
Bnodes,reversesubListreverses them and returns the new head of the group, plus the first node of the next group. - In
reverseList, we track the end of the previous reversed group (last_of_prev) to link it to the start of the current reversed group. - The
startvariable keeps track of the new head of the entire modified list (the head of the first reversed group).
This should resolve the type error and correctly reverse the linked list in groups of K nodes as required.
内容的提问来源于stack exchange,提问作者K2G

