A carousel shows its slides in a linked list. For a two-row layout, the designer wants the slides in odd positions (1st, 3rd, 5th, ...) first, followed by the slides in even positions (2nd, 4th, ...).
Write oddThenEven(head) that regroups the nodes this way and returns the new head. Positions count from 1 and refer to the original order, not to the values. Inside each group, keep the original order. Use O(1) extra space by relinking the nodes.
Input: head = [1,2,3,4,5] Output: [1,3,5,2,4]
Positions 1, 3, 5 hold 1, 3, 5; positions 2, 4 hold 2, 4.
Input: head = [20,10,30,50,40,60] Output: [20,30,40,10,50,60]
The odd positions hold 20, 30, 40 and the even ones 10, 50, 60.
0 to 10^4 nodes.-10^6 <= node.val <= 10^6Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.
Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #227 Odd Slots Before Even Slots. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.