Reverse Nodes in k-Group
The key idea
Reverse each block of
k nodes in place, but only after you confirm a full group of k exists ahead. Keep a prev_group_tail that points at the last node of the already-finished part, so each reversed block can be stitched back onto the chain in the right order.Problem
Given the head of a linked list, reverse the nodes of the list k at a time and return the modified list.k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, then the nodes that are left out at the end should remain as is.
You may not alter the values in the list's nodes — only the nodes themselves may be changed.
Constraints
- The number of nodes in the list is
n 1 <= k <= n <= 5000- `0 <= Node.val <= 1000
Examples
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Linked List problems
- Add Two NumbersMEDIUM
- Copy List with Random PointerMEDIUM
- Design Linked ListMEDIUM
- Insert Greatest Common Divisors in Linked ListMEDIUM
- Intersection of Two Linked ListsEASY
- Maximum Twin Sum of a Linked ListMEDIUM
- Merge Two Sorted ListsEASY
- Odd Even Linked ListMEDIUM
- Partition ListMEDIUM
- Remove Duplicates from Sorted List IIMEDIUM
- Remove Linked List ElementsEASY
- Remove Nth Node From End of ListMEDIUM