sagelearnai

Odd Even Linked List

Difficulty: Medium · Pattern: Linked List · LeetCode #328

Group all nodes at odd positions (1st, 3rd, …) first, followed by those at even positions, preserving the relative order within each group. O(1) extra space, O(n) time.

Examples

text
1 → 2 → 3 → 4 → 5       →  1 → 3 → 5 → 2 → 4
2 → 1 → 3 → 5 → 6 → 4 → 7 →  2 → 3 → 6 → 7 → 1 → 5 → 4

Hints

  1. Maintain two chains, odd and even, by alternately linking nodes.
  2. Remember the head of the even chain to attach it at the end.

Approach

odd = head, even = head.next, evenHead = even. While even and even.next exist: odd.next = even.next; odd = odd.next; even.next = odd.next; even = even.next. Finally odd.next = evenHead. O(n), O(1).

Complexity

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

Python solution
def oddEvenList(head):
    if not head:
        return head
    odd, even = head, head.next
    even_head = even
    while even and even.next:
        odd.next = even.next; odd = odd.next
        even.next = odd.next; even = even.next
    odd.next = even_head
    return head
JavaScript solution
function oddEvenList(head) {
  if (!head) return head;
  let odd = head, even = head.next; const 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;
}