hardLinked ListPure DSA~40 min
Reverse Log Segments In K-Groups
A append-only log is a singly linked list of entries. To render it in reverse-chronological blocks, reverse every consecutive group of k nodes; a trailing group smaller than k stays in original order.
Problem
Given the head of a linked list, reverse the nodes k at a time and return the modified list. Nodes in a final group of fewer than k remain as-is. Only node links may be changed, not values.
Input
The head of a singly linked list of n nodes and an integer k (1 ≤ k ≤ n ≤ 5000).
Output
The head of the list after k-group reversal.
Constraints
- 1 ≤ k ≤ n
- Reverse by relinking nodes, not by swapping values
- O(n) time, O(1) extra space
Examples
Example 1
Input
list = 1->2->3->4->5, k = 2
Output
2->1->4->3->5
Pairs reversed; the lone trailing 5 is left alone.
Example 2
Input
list = 1->2->3->4->5, k = 3
Output
3->2->1->4->5
First triple reversed; trailing 4->5 (fewer than 3) unchanged.