Reverse nodes in groups of : given and , produce .
The pattern:
Check if nodes remain
Reverse those nodes
Connect to previously processed part
Recurse or iterate for the rest
def reverseKGroup(head, k):
# Check if k nodes exist
count = 0
node = head
while node and count < k:
node = node.next
count += 1
if count < k:
return head # don't reverse
# Reverse k nodes, recurse for rest
newHead = reverse(head, k)
head.next = reverseKGroup(node, k)
return newHead
Time: . Space: for recursion, or iteratively.