LeetCode #328 Medium

Odd Even Linked List

Group nodes at odd positions before nodes at even positions, preserving relative order.

linked-listtwo-pointers
Open on LeetCode ↗
02

Intuition

💡

Read the title too fast and you will group by VALUE - odd numbers first, even numbers second. The problem means the node's POSITION, counting from 1, and the values are irrelevant. Once that is clear the shape is two chains woven through one list: odd collects positions 1, 3, 5 and even collects 2, 4, 6, each advancing by two. The bug that survives testing is forgetting to terminate the even chain. You join the odd tail to the even head at the end, but the even tail still points at whatever followed it in the original list - which is a node now living in the odd chain - so the list closes into a cycle and any traversal hangs forever. Setting the even tail's next to None is the line that makes it correct, and it is the one people leave out.

03

Approach

1

Read position, not value

Index from 1: the head is position 1 and therefore odd. Nothing about the stored values matters here, which is worth stating explicitly because the problem name actively misleads on this point.

2

Weave two pointers

Hold odd at the current odd node and even at the current even node, remembering evenHead so you can attach it later. Each iteration sets odd.next = even.next then advances odd, then even.next = odd.next then advances even. Both chains grow in place with no new nodes allocated.

3

Join and terminate

After the loop, odd is the last odd node and points it at evenHead. The even chain's final node must already end in None, which it does because the loop stops when even or even.next is exhausted - but only if you never re-pointed it afterwards. Getting this wrong creates a cycle rather than a wrong answer, which is why it shows up as a hang instead of a failed assertion.

04

Solution & live demo

python
1class Solution:
2 def oddEvenList(self, head):
3 if not head or not head.next:
4 return head
5 odd = head
6 even = head.next
7 even_head = even
8 while even and even.next:
9 odd.next = even.next
10 odd = odd.next
11 even.next = odd.next
12 even = even.next
13 odd.next = even_head
14 return head
05

Edge cases

Fewer than three nodes

Already grouped; return head unchanged.

Even number of nodes

The even chain ends naturally at the last node.

Odd number of nodes

The odd chain gains the final node; even terminates before it.

Empty list

Return None before touching any pointer.

06

Complexity

Time
O(n)
Space
O(1)
One pass, pointers only. No nodes are created or copied.