Skip to content
Problem 328 · LeetCode 328(opens in a new tab)

Odd Even Linked List

MediumLinked lists

You get the head of a singly linked list. Count the nodes from 1: the first node is at an odd position, the second at an even one, the third at an odd one again, and so on.

Rearrange the list so that every node at an odd position comes first, followed by every node at an even position. Inside each group, keep the nodes in the order they had. Return the head of the rearranged list.

Aim for O(n) time and O(1) extra memory: move the existing nodes rather than making new ones.

Example 1

Input:  head = [8, 5, 2, 6, 1]
Output: [8, 2, 1, 5, 6]
Why:    positions 1, 3, 5 hold 8, 2, 1; positions 2, 4 hold 5, 6
2 more examples and the constraints

Example 2

Input:  head = [4, 7, 1, 9, 3, 2]
Output: [4, 1, 3, 7, 9, 2]
Why:    odd positions give 4, 1, 3; even ones give 7, 9, 2

Example 3

Input:  head = []
Output: []
Why:    there is nothing to move

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • −1,000,000 ≤ each node's value ≤ 1,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Copy values out and backO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeExtra memory for 10,000 nodesVerdict
Copy values out and backO(n)
Correct; breaks the memory limit
Two chains in placeO(n)
Best; constant extra memory

n = number of nodes. Both are linear in time; they differ in memory.

Edge cases to test

  • Empty list. head is null; return it without reading head.next.
  • One or two nodes. [42] and [3, −3] are already in the right order; the loop never runs.
  • Even number of nodes. [4, 7, 1, 9, 3, 2]: the even chain ends on the last node, whose next is already null.
  • Repeated values. Positions decide the groups, not values, so [5, 5, 5, 5] comes back unchanged.

Common mistakes

  • Grouping by whether the value is odd instead of whether the position is odd.
  • Forgetting to save the start of the even chain, so it cannot be attached at the end.
  • Leaving the last even node pointing at an odd node, which makes a cycle.

How to talk through it

  1. 1Clarify. Odd means position, counted from 1, not the value? Must the order inside each group stay the same?
  2. 2Start simple. Copy the values into two lists and write them back: O(n) time, but O(n) memory.
  3. 3Name the trick. The node after the even tail is the next odd node, and the node after that is the next even one. Two tails can leapfrog.
  4. 4Code the loop. Save the even head, run while even and even.next exist, then join the chains.
  5. 5Test out loud. Run the empty list, one node, and an even-length list before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?