codejump
MediumPythonJavaScriptTypeScript

Linked List — Odd Even Linked List

Data StructuresLinked ListTwo Pointers

solve(values) builds a singly linked list from values, regroups it so that **all
nodes at odd positions come first, followed by all nodes at even positions**, and returns
the values. Positions are 1-based (the head is position 1) and the **relative order inside
each group is preserved**. Note it is the *position* that counts, not the value.

Do it in O(n) time and O(1) extra space by re-linking nodes: keep an odd tail and an
even tail, and remember where the even chain starts so you can attach it at the end.

Examples

solve([1,2,3,4,5])          → [1,3,5,2,4]
solve([2,1,3,5,6,4,7])      → [2,3,6,7,1,5,4]
solve([1,2])                → [1,2]

Sample tests

Test #1Odd length
Input: [[1,2,3,4,5]]
Output: [1,3,5,2,4]
Test #2Positions, not values
Input: [[2,1,3,5,6,4,7]]
Output: [2,3,6,7,1,5,4]
Test #3Two nodes
Input: [[1,2]]
Output: [1,2]