Reverse the nodes of a singly linked list in groups of size .
Given the head of a singly linked list and an integer , reverse the nodes of the list at a time.
- If the number of nodes in the current group is exactly , reverse that group in place.
- If the remaining nodes at the end contain fewer than nodes, leave them in their original order.
- You must rearrange the node links; do not create a new list from the values.
Return the head of the modified list.
Input Format
- A singly linked list represented by its head node.
- An integer with .
Output Format
Return the head node of the linked list after reversing every consecutive block of nodes.
Constraints
- The list length is at least $0$.
- .
- Each node appears in exactly one position in the final list.
- The solution should work in-place with extra list storage, aside from recursion stack if a recursive approach is used.
Example 1
Input
head = [1,2,3,4,5], k = 2
Output
[2,1,4,3,5]
Explanation
The list is split into groups of 2: [1,2], [3,4], and [5]. The first two groups are reversed, while the last group has fewer than 2 nodes and stays unchanged.
Example 2
Input
head = [1,2,3,4,5], k = 3
Output
[3,2,1,4,5]
Explanation
The first group [1,2,3] is reversed. The remaining nodes [4,5] are fewer than 3, so they remain in place.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.