Odd Even Linked List

medium

Given the head of a singly linked list, regroup it so that every node in an odd position comes first, followed by every node in an even position. Position is counted from 1: the first node is odd, the second is even, the third is odd, and so on — this is about a node's place in the list, not the value stored in it.

Within each group the nodes must keep their original relative order. Return the head of the regrouped list.

You must do this using only O(1) extra space and O(n) time — rewire the existing nodes, don't build a copy.

Hints

You don't need to move node values around — think about relinking the next pointers you already have.
Walk two nodes at a time: from an odd node, the next odd node is exactly two hops away (node.next.next).
Grow two chains at once — an odd chain and an even chain — then join the even chain onto the tail of the odd chain. Save the even head before you start.

Common doubts

Its position in the list (1-indexed), not node.val. The first node is odd, the second even, regardless of the numbers stored.
The loop leaves odd pointing at the last odd node; to finish you attach the whole even chain with odd.next = evenHead. Without saving it, you'd have no handle on the start of the even chain.
even always trails odd by one node, so even (and even.next) become null first. Checking even and even.next guarantees every pointer you dereference exists.

Interview follow-ups

Same two-chain weave, but the test switches from position parity to node.val % 2; the relinking logic is identical.
Keep k tail pointers and an array of k heads; deal each node to bucket i % k, then chain the k sublists together in order.

Fun facts

  • The trick is the same one a card dealer uses: deal alternately into two piles, then stack one pile on the other — no card is ever copied.
  • This weave-two-chains-then-join pattern reappears when splitting a list for merge sort and when reordering a list into first-last-second-secondlast order.

Asked at

AmazonMicrosoftGoogleAdobeBloomberg
Frequently Sometimes Occasionally
Example 1
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Odd positions 1,3,5 hold 1,3,5; even positions 2,4 hold 2,4. Odd group first, then even group.
Example 2
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Odd positions hold 2,3,6,7; even positions hold 1,5,4. Concatenate odd then even.
Constraints

- The number of nodes in the list is in the range [0, 10^4]. - -10^6 <= Node.val <= 10^6

Solve this problem →