Odd Even Linked List

Medium Linked List

head is the head of a singly linked list, which may be empty. Its nodes are numbered from 1: the head is node 1, the node after it node 2, and so on.

Rearrange the list so that the odd-numbered nodes come first and the even-numbered nodes after them, each group in the order it had. It is the nodes' numbers that count, not their values.

Return the head of the rearranged list, or null if the list is empty.

Example 1

Input: head = [4,9,-1,6,3,8]
Output: [4,-1,3,9,6,8]

Nodes 1, 3 and 5 hold 4, -1 and 3; nodes 2, 4 and 6 hold 9, 6 and 8. The odd-numbered nodes come first, then the even-numbered, each group in its old order.

Example 2

Input: head = [5,5,2,2,7]
Output: [5,2,7,5,2]

Example 3

Input: head = []
Output: []

An empty list stays empty.

Constraints

  • 0 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Linked List

All Linked List problems