Reverse Nodes in k-Group
You are given the head of a linked list and a positive integer k. Split the list into consecutive groups of k nodes, starting from the head, and reverse the nodes inside each group. If the last group has fewer than k nodes, leave it in its original order.
Rewire the nodes rather than swapping their values, use O(1) extra memory, and return the new head of the list.
Constraints
- The list has between
0and5000nodes. 0 <= Node.val <= 10001 <= k <= 5000(kmay be larger than the length of the list)
Examples
Example 1
Input: head = [1,2,3,4,5,6,7,8], k = 3 Output: [3,2,1,6,5,4,7,8]
Groups [1, 2, 3] and [4, 5, 6] are reversed. Only 7 and 8 are left, fewer than 3, so they stay in order.
Example 2
Input: head = [1,2,3,4,5], k = 1 Output: [1,2,3,4,5]
Groups of one node are already reversed: the list doesn't change.
Example 3
Input: head = [1,2,3,4], k = 4 Output: [4,3,2,1]
k equals the length, so the whole list is one group and is fully reversed.
JavaScript you'll use: Linked list and tree nodes Destructuring, spread and rest
/**
* Linked list nodes are provided (you don't need to define them):
* class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
function reverseKGroup(head, k) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.