Swap Neighboring Blocks
Cut the list into blocks of k nodes from the front. Swap the first block with the second, the third with the fourth, and so on. Inside a block the order stays as it is.
Only two full blocks are swapped: when fewer than 2 * k nodes remain at the end, those nodes stay where they are. Return the head. For 1 -> 2 -> 3 -> 4 -> 5 and k = 2 the result is 3 -> 4 -> 1 -> 2 -> 5. 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
The blocks 1, 2 and 3, 4 trade places. The 5 has no full pair of blocks and stays.
Example 2
Two pairs of blocks: 3, 4 moves in front of 1, 2, and 7, 8 in front of 5, 6.
Example 3
Three nodes are fewer than two blocks of two.
Constraints
0 <= number of nodes <= 60-100 <= node.val <= 1001 <= k <= 60
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Alternating SumBeginner
- Are the Lists EqualBeginner
- Average of the ValuesBeginner
- Balanced Open and CloseBeginner
- Binary Linked List to IntegerBeginner
- Build a Linked List From an ArrayBeginner
- Build a List of DigitsBeginner
- Build a Range ListBeginner