Reverse a Linked List in Groups of K
Implement reverseKGroup
Given the head of a singly linked list and an integer
k, reverse every consecutive group of k nodes. If the number of nodes remaining at the end isn't a full group of k, leave that final partial group exactly as it is.
The optimal solution never reverses a group speculatively — it always peeks k nodes ahead with a throwaway check pointer first, confirming a full group exists before touching a single .nextLook Before You LeapReversing pointers is easy to do but hard to undo cleanly mid-way. Confirming the precondition (a full group of k nodes) BEFORE any relinking starts means the algorithm never has to detect a failure partway through and unwind it — by the time reversal begins, success is already guaranteed. pointer. Once confirmed, each group is reversed with the same three-pointer dance used to reverse an entire list, and a trailing groupPrev — anchored at the previous group's original first node, now its tail — links each freshly-reversed group to the next.
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]
Example 3:
Input: head = [1,2,3,4], k = 1
Output: [1,2,3,4]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in head ≤ 200 - ●
-1000 ≤ node value ≤ 1000 - ●
1 ≤ k ≤ number of nodes in head
head =
[1, 2, 3, 4, 5]
k =
2