Problem · Linked List
Reverse Nodes in K-Group
Learn this problemProblem statement
Given the head head of a singly linked list and a positive integer k, reverse the nodes of the list in consecutive groups of exactly k nodes.
If fewer than k nodes remain at the end, leave that final group unchanged. Return the head of the transformed list.
You may change node links, but you must not change node values.
Function
reverseKGroup(head: ListNode, k: int) → ListNodeExamples
Example 1
head = [1,2,3,4,5]k = 2return = [2,1,4,3,5]The complete groups [1, 2] and [3, 4] are reversed. The final one-node group remains unchanged.
Example 2
head = [1,2,3,4,5]k = 3return = [3,2,1,4,5]The first three nodes form one complete group and are reversed. Only two nodes remain, so their order is preserved.
Constraints
- The list contains between
1and5000nodes. -1000 <= node.val <= 10001 <= k <= number of nodes- The input list is finite and contains no cycle.