Reverse Even Length Groups
Split the list into groups of sizes 1, 2, 3, 4, ... in order. The last group may be shorter than planned, and its size is whatever is left. Reverse every group whose size is even, leave the odd-sized groups alone, and return the head. For 1 -> 2 -> 3 -> 4 -> 5 -> 6 the groups are [1] [2,3] [4,5,6], so only [2,3] is reversed. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
head [1,2,3,4,5,6]
returns [1,3,2,4,5,6]
Groups [1] [2,3] [4,5,6]: only [2,3] flips.
Example 2
head [1,2,3,4,5]
returns [1,3,2,5,4]
The last group is [4,5], which has size 2, so it flips.
Constraints
0 <= number of nodes <= 100-100 <= Node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Reverse the Second HalfMedium
- Rotate ListMedium
- Sort ListMedium
- Split Linked List in PartsMedium
- Swap Kth From Start and EndMedium
- Where the Cycle StartsMedium
- Complete the MirrorHard
- Deal and WeaveHard