Problem
You get the head of a linked list and a number k. Reverse the nodes `k` at a time: the first k nodes flip, then the next k, and so on. If fewer than k nodes are left at the end, leave them as they are. Relink the nodes themselves rather than swapping values, and return the new head.
Example 1
- Input
- 1
- Output
- 2 -> 3 -> 4 -> 5, k = 2 → 2 -> 1 -> 4 -> 3 -> 5
Example 2
- Input
- 1
- Output
- 2 -> 3 -> 4 -> 5, k = 3 → 3 -> 2 -> 1 -> 4 -> 5
Example 3
- Input
- 1
- Output
- 2 -> 3 -> 4 -> 5, k = 1 → 1 -> 2 -> 3 -> 4 -> 5
Try to use only O(1) extra memory.
Constraints
1 <= k <= number of nodes <= 50000 <= Node.val <= 1000