Reverse Linked-List Nodes in Groups of K
Problem statement
Given the head of a singly linked list and an integer k, reverse the nodes in each complete consecutive group of k nodes. If the final group contains fewer than k nodes, leave it in its original order.
Change node links rather than swapping stored values. Return the new head. For this exercise, assume the list is nonempty, contains distinct values and has no cycle. The input and output display each list as an array, from its head to its tail.
Function
reverseKGroup(head: ListNode, k: int) → ListNodeExamples
Example 1
head = [1,2,3,4,5]k = 2return = [2,1,4,3,5]Reverse each pair; the one-node tail stays unchanged.
Example 2
head = [1,2,3,4,5]k = 3return = [3,2,1,4,5]Only the first three nodes form a complete group.
Constraints
- For this exercise, assume
1 <= n <= 1000, where n is the number of nodes. 1 <= k <= n.- Node values are distinct integers in
[-10^9,10^9]. - A short final group is unchanged.