143. Reverse Nodes in k-Group

Hard · Linked List

Given a linked list, reverse the nodes of the list k at a time, and return the modified list. If the number of nodes is not a multiple of k, then left-out nodes, in the end, should remain as is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

The linked list is represented as an array where each element is a node value. For example, [1,2,3,4,5] represents the list 1→2→3→4→5.

Examples

Example 1
Input: list = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Explanation: Reverse the first 2 nodes: 1→2 becomes 2→1. Reverse the next 2 nodes: 3→4 becomes 4→3. Node 5 is left as is since there are fewer than k nodes remaining.
Example 2
Input: list = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Explanation: Reverse the first 3 nodes: 1→2→3 becomes 3→2→1. Nodes 4 and 5 are left as is since there are fewer than k nodes remaining.

Constraints