Reverse Nodes in k-Group
Given the head of a linked list, reverse the nodes k at a time and return the modified list. If the number of remaining nodes is fewer than k, leave them as they are. Node values must not be changed, only the links.
Open official problem prompt ↗Reverse the list in consecutive chunks of size k in place, leaving any final chunk shorter than k unchanged.
Like flipping fixed-length train cars on a track: you detach a block of k cars, reverse their order, reattach it, and move on, leaving a short final block untouched.
- Input
- head = [1,2,3,4,5], k = 2
- Output
- [2,1,4,3,5]
- Why
- The first two nodes reverse to 2,1; the next two to 4,3; the leftover single node 5 stays in place.
The number of nodes is n1 <= k <= n <= 50000 <= Node.val <= 1000