Description
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 ≤ list length. If the number of remaining nodes is less than k, leave them as is.
Examples
Input:
head = [1,2,3,4,5], k = 2Output:
[2,1,4,3,5]Explanation:
Reverse every 2 nodes. 5 is left as is.
Input:
head = [1,2,3,4,5], k = 3Output:
[3,2,1,4,5]Explanation:
Reverse first 3 nodes. Last 2 are left as is.
Input:
head = [1,2,3,4,5,6,7,8], k = 4Output:
[4,3,2,1,8,7,6,5]Explanation:
Reverse every 4 nodes. First group [1,2,3,4] becomes [4,3,2,1], second group [5,6,7,8] becomes [8,7,6,5]. With exactly 8 nodes and k=4, both groups are complete and get reversed.
Constraints
- •
The number of nodes is n. - •
1 ≤ k ≤ n ≤ 5000 - •
0 ≤ Node.val ≤ 1000