Reverse Nodes in k-Group
HardLinked List
You are given head, the first node of a singly linked list, and a positive integer k. Split the list into consecutive groups of k nodes starting from the head, reverse the nodes within each full group, and return the head of the modified list.
If the last group has fewer than k nodes, leave it in its original order.
Only relink nodes; do not change the values stored in them.
Follow-up: can you do it with O(1) extra memory?
Example 1
- Input:
- head = [1,2,3,4,5,6,7], k = 3
- Output:
- [3,2,1,6,5,4,7]
- Explanation
- The groups are [1,2,3], [4,5,6] and [7]. The two full groups are reversed; [7] has fewer than 3 nodes, so it is left as is.
Example 2
- Input:
- head = [5,10,15,20,25,30], k = 2
- Output:
- [10,5,20,15,30,25]
- Explanation
- Each pair is swapped: (5,10) becomes (10,5), and so on. The length is a multiple of 2, so nothing is left over.
Example 3
- Input:
- head = [6,1,8,3], k = 4
- Output:
- [3,8,1,6]
- Explanation
kequals the length, so the entire list is reversed.
Constraints
- The number of nodes
nis in the range[1, 5000] 1 <= k <= n0 <= Node.val <= 1000