Reverse in Groups of k
HardLinked lists
You are given the head of a linked list and a number k. Reverse the nodes of the list k at a time and return the new head. If the number of nodes is not a multiple of k, the nodes left over at the end stay in their order.
Only change where the nodes point: don't change the values inside them.
Lists in the examples are written as their values from head to tail: [1,2,3] is 1 → 2 → 3, and [] is an empty list, with no head at all.
Try it using only a few extra pointers, not a copy of the list.
Constraints
- 1 ≤
k≤ number of nodes ≤ 5,000 - 0 ≤ node value ≤ 1,000
Example 1
Input
head = [1,2,3,4,5]
k = 2
Output
[2,1,4,3,5]
Why:
The groups 1 2 and 3 4 are reversed; 5 is left over and stays where it is.
Example 2
Input
head = [1,2,3,4,5]
k = 3
Output
[3,2,1,4,5]
Why:
1 2 3 is reversed; 4 5 is fewer than 3 nodes and stays.
Hints
Was this a good challenge?
- Solved by
- 0
- Submissions
- 0
- Accepted
- –