Reverse Nodes in k-Group
Given the head of a linked list, reverse its nodes k at a time and return the modified head. Nodes are reversed in consecutive blocks of exactly k; if the final block has fewer than k nodes, it is left in its original order. Rewire nodes in place — do not change any node's value. Return the head of the fully rewired list.
- 1 <= k <= n <= 5000
- 0 <= Node.val <= 1000
- O(1) extra memory is required (no recursion stack).
head = [1,2,3,4,5], k = 2[2,1,4,3,5]head = [1,2,3,4,5], k = 3[3,2,1,4,5]head = [1,2], k = 1[1,2]Instead of reversing the whole list, we want to reverse it in "chunks" of a specific size, k. It's like taking a long chain, cutting it into pieces of length k, flipping those pieces, and then welding them back together.
The most important rule is that if a piece is shorter than k, we leave it exactly as it is. So, before we start any reversal, we "scout" ahead to see if there are at least k nodes waiting for us. If we hit the end of the list too early, we stop and leave that last bit alone.
Once we know we have a full group of k, we reverse it. We use the same technique as a standard list reversal: we flip the arrows one by one until the last node in the group becomes the first.
The trickiest part is making sure the "tail" of one flipped group points to the "head" of the next flipped group. We use a Dummy Node at the very beginning to help us manage the first flip, and a moving pointer to keep track of the last node we processed.
# 1. Scout ahead to check if k nodes exist
curr = head
for _ in range(k):
if not curr: return head # Not enough nodes, leave as is
curr = curr.next
# 2. Reverse the k nodes
prev, curr = None, head
for _ in range(k):
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
# 3. Stitch and recurse
# Head is now the tail of this flipped group.
# Point its next to the result of the next group.
head.next = reverseKGroup(curr, k)
return prev # New head of this segmentBlock-by-Block Reversal
counting nodes...