7.17 Odd Even Linked List

7.17.1 Problem Metadata

7.17.2 Description

Group odd-position nodes followed by even-position nodes.

7.17.3 Solution - Two Pointers

7.17.3.1 Walkthrough

Maintain two pointers odd and even, and a evenHead. Traverse the list, linking odd nodes to odd nodes and even nodes to even nodes. Finally, connect the tail of the odd list to evenHead.

7.17.3.2 Analysis

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

7.17.3.3 Code - Java

public ListNode oddEvenList(ListNode head) {
    if (head == null) return null;
    ListNode odd = head;
    ListNode even = head.next;
    ListNode evenHead = even;
    while (even != null && even.next != null) {
        odd.next = even.next;
        odd = odd.next;
        even.next = odd.next;
        even = even.next;
    }
    odd.next = evenHead;
    return head;
}