Reverse Nodes in K-Group
Cut the list into consecutive groups of k nodes and reverse each group. If the last group has fewer than k nodes, leave it as it is. Return the new head. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
head [1,2,3,4,5]
k 2
returns [2,1,4,3,5]
2,1 then 4,3 then the lone 5.
Example 2
head [1,2,3,4,5]
k 3
returns [3,2,1,4,5]
3,2,1 then the short group 4,5 stays.
Constraints
0 <= number of nodes <= 1001 <= k <= 100-100 <= Node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Smallest TurnHard
- Subtract Two NumbersHard
- Swap Neighboring BlocksHard
- Alternating SumBeginner
- Are the Lists EqualBeginner
- Average of the ValuesBeginner
- Balanced Open and CloseBeginner
- Binary Linked List to IntegerBeginner