Reverse nodes in groups of k
Hardlinked listrecursion
Reverse each consecutive group of k nodes. If the last group has fewer than k nodes, leave it as it is. Change the links, not the values, using O(1) extra memory.
Example 1
Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5]
Example 2
Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5]
Constraints
- 1 ≤ k ≤ number of nodes ≤ 5000
- 0 ≤ Node.val ≤ 1000
Submit checks your solution against 9 tests, including hidden ones.
// Provided by the judge: keep these definitions
class ListNode {
constructor(val = 0, next = null) {
this.val = val
this.next = next
}
}
/**
* @param {ListNode|null} head
* @param {int} k
* @return {ListNode|null}
*/
function reverseKGroup(head, k) {
}