Reverse Nodes in k-Group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, the remaining nodes at the end should stay in their original order.
You may not alter the values in the list's nodes; only the nodes themselves may be changed.
Example 1
[1] -> [2] -> [3] -> [4] -> [5] -> null --- [2] -> [1] -> [4] -> [3] -> [5] -> null
Input
head = [1,2,3,4,5], k = 2Output
[2,1,4,3,5]The nodes are reversed in pairs: 1 and 2 become 2 and 1, and 3 and 4 become 4 and 3; node 5 remains as is.
Example 2
[1] -> [2] -> [3] -> [4] -> [5] -> null --- [3] -> [2] -> [1] -> [4] -> [5] -> null
Input
head = [1,2,3,4,5], k = 3Output
[3,2,1,4,5]The first three nodes are reversed as one group, while the remaining two nodes stay in their original order.
Constraints
- The number of nodes in the list is n
- 1 <= k <= n <= 5000
- 0 <= Node.val <= 1000