Odd Even Linked List

Group the nodes at odd positions first, then the nodes at even positions, by threading two chains through the list and joining them at the end.

Time O(n)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Positions alternate odd, even, odd, even. Keep two tails: odd at the end of the odd chain and even at the end of the even chain. The node after even is always the next odd one, so hang it on odd; the node after that is the next even one, so hang it on even. When the list runs out, point the last odd node at evenHead, the first even node you saved at the start.

Code

public ListNode OddEvenList(ListNode head) {
    if (head == null) return null;
    ListNode odd = head, even = head.next, evenHead = even;
    while (even != null && even.next != null) {
        odd.next = even.next; // skip over the even node
        odd = odd.next;
        even.next = odd.next; // skip over the new odd node
        even = even.next;
    }
    odd.next = evenHead; // odd chain, then the even chain
    return head;
}

Tips

In the .NET library

The rewiring changes only next references; no ListNode is created, so the extra space is O(1).