Odd Even Linked List
Reorder a singly linked list such that all nodes at odd indices (1st, 3rd, 5th...) come first, followed by all nodes at even indices (2nd, 4th, 6th...). The relative order within each group must be preserved.
- The number of nodes is in the range [0, 10,000]
- -1,000,000 <= Node.val <= 1,000,000
- Must solve in **O(1) extra space** and **O(N) time**.
head = [1,2,3,4,5][1,3,5,2,4]head = [2,1,3,5,6,4,7][2,3,6,7,1,5,4]head = [1][1]Rearranging a linked list by position means grouping all nodes at odd indices (1st, 3rd, 5th...) at the beginning, followed by all nodes at even indices (2nd, 4th, 6th...). This must happen in-place to satisfy memory constraints.
The most intuitive way is to traverse and collect nodes into two separate arrays (odds and evens) and then link them. However, this uses O(N) extra space. To optimize to O(1) space, we must manipulate pointers directly.
We build two concurrent chains using three roles: an odd writer, an even writer, and an evenHead safety anchor that stays at the start of the even chain so we can bridge the two halves later.
As we move through the list, we perform a "leapfrog" surgery. The odd pointer skips over the current even node to link to the next available odd node. Then, the even pointer skips over the new odd node to link to the next even node.
odd = head
even = head.next
even_head = even
# even and even.next must exist to leapfrog
while even and even.next:
# 1. Odd jumps over even
odd.next = even.next
odd = odd.next
# 2. Even jumps over the new odd
even.next = odd.next
even = even.next
# 3. The Bridge: Link the end of odd to the start of even
odd.next = even_headThe loop handles both even and odd length lists automatically. In even-length lists, even.next becomes null; in odd-length lists, even itself becomes null. In both cases, the odd pointer finishes at the true end of the odd chain.
Step 2: First Leapfrog
Step 3: Second Leapfrog
Step 4: The Bridge Stitch
Relative Parity Transformation
Operation Step
Phase 1: Dual Track Setup
We launch two independent cursors. Odd claims the first node, while Even takes the second. We cache the Even Head as an anchor for the final re-join.
We are essentially threading two disjoint lists through the same memory space, then tying them together at the midpoint.
By advancing cursors two nodes at a time, we reorganize the entire topology in a single O(N) pass using just O(1) extra space.