Reverse Nodes in k-Group
Part of Practice: Design & Hard Surgery
Given the head of a linked list and an integer k, reverse the nodes k at a time: the first k nodes get reversed among themselves, then the next k, and so on. If fewer than k nodes remain at the end, leave that tail segment in its original order.
You must rearrange the actual nodes (no swapping values), and the expected solution uses O(1) extra memory. The list has up to 5000 nodes and k is between 1 and the list length.
Examples
- Input:
- head = [1, 2, 3, 4, 5], k = 2
- Output:
- [2, 1, 4, 3, 5]
Pairs (1,2) and (3,4) are each reversed; the leftover single node 5 stays put.
- Input:
- head = [1, 2, 3, 4, 5], k = 3
- Output:
- [3, 2, 1, 4, 5]
Only the first three nodes form a full group; the remaining two are fewer than k, so they keep their order.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.