Odd Even Linked List

Reorder a list so odd-indexed nodes come first, then even-indexed, preserving relative order — two interleaved chains.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
linked-list

Problem#

Reorder a singly linked list so that all odd-indexed nodes (1-indexed) come before all even-indexed nodes, preserving relative order in each group. Do it in O(1) extra space.

Examples#

  • [1,2,3,4,5][1,3,5,2,4]
  • [2,1,3,5,6,4,7][2,3,6,7,1,5,4]

Constraints#

  • 0 <= n <= 10^4.

Approach#

Maintain two interleaved chains: odd and even, each starting at the first/second node and stepping by 2. After the loop, link the odd tail to the even head.

Solution#

Odd Even Linked List
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head) return head;
ListNode *odd = head, *even = head->next, *evenHead = even;
while (even && even->next) {
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = evenHead;
return head;
}
};

Editorial#

Both chains weave forward simultaneously, each picking nodes at stride 2. The loop guard handles both odd and even total lengths. After the weave, the odd chain points at evenHead to form the final list.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.