Use a dummy head, and
l, r : define reversing range
pre, cur : used in reversing, standard reverse linked linked list method
jump : used to connect last node in previous k-group to first node in following k-group
def reverseKGroup(self, head, k): dummy = jump = ListNode(0) dummy.next = l = r = head while True: count = 0 while r and count < k: # use r to locate the range r = r.next count += 1 if count == k: # if size k satisfied, reverse the inner linked list pre, cur = r, l for _ in range(k): cur.next, cur, pre = pre, cur.next, cur # standard reversing jump.next, jump, l = pre, l, r # connect two k-groups else: return dummy.next
Can you explain how the 3 variable tuple unpacking works ? If I unwind it , I usually get
AttributeError: 'NoneType' object has no attribute 'next'
@rahul8590 Python multiple value assignments work by first evaluating the right hand side.
All variables on the right-hand side are first evaluated and then assigned to the left hand-side variables going from left->right.
@rahul8590 Also, all previous values are considered. (values of all variables before the statement)
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.