Skip to the code
cf.
+25 XP

#227 Odd Slots Before Even Slots

medium

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.

Example 1

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.

Example 2

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.

Constraints

  • The list has 0 to 10^4 nodes.
  • -10^6 <= node.val <= 10^6

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

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).