Odd Even Linked List

Move the nodes at odd positions of a linked list to the front and the even ones after them, by relinking the nodes in place.

Given the head of a singly linked list, rearrange it so that the nodes at odd positions come first, followed by the nodes at even positions, and return the head. The first node is at position 1, the second at position 2, and so on. Inside each group the nodes keep their original order. Use O(1) extra space and O(n) time.

Example 1
Input: head = [1, 2, 3, 4, 5]
Output: [1, 3, 5, 2, 4]
Example 2
Input: head = [2, 1, 3, 5, 6, 4, 7]
Output: [2, 3, 6, 7, 1, 5, 4]
Explanation: the positions decide the groups, not the values.
Solution

The Idea

Picture a train of five cars, coupled one behind the other and numbered 1 to 5 from the front. The task is to recouple them so that cars 1, 3 and 5 run first and cars 2 and 4 follow. No car leaves the track; only the couplings change.

A linked list works the same way. Each node holds a value and a link, called next, to the node behind it, and the list is reached through its first node, the head. To get to the fourth node, you start at the head and follow next three times. There is no way to jump straight to a position, as an array allows.

Example 2 shows that only positions count. In [2, 1, 3, 5, 6, 4, 7], the nodes at positions 1, 3, 5 and 7 hold 2, 3, 6 and 7, so those come first. The value 1 is odd, but it sits at position 2, so it moves to the second group with 5 and 4.

Building a new list in the new order would be easy, but the problem allows only a fixed amount of extra memory, however long the list is. So the nodes must stay where they are, and only their next links may change. Which links have to change?

Look at the list [1, 2, 3, 4, 5] again. The node after node 1 in the answer is node 3, which is two steps ahead in the original list. The same holds for every node: its new neighbour is the one it used to reach in two steps. So if each node skips over the node right behind it, the list falls apart into two lists, which we will call chains. Look at the picture below.

The list 1, 2, 3, 4, 5 with positions 1 to 5. Split by position, it becomes the odd chain 1, 3, 5 and the even chain 2, 4, which starts at the first even node, node 2. Node 5 is then joined to node 2.

The row labelled "the list" shows the five nodes, with the odd positions in blue and the even ones in green. In the part labelled "split by position", node 1 links to 3 and node 3 to 5: that is the odd chain. Node 2 links to 4: that is the even chain, and its first node, node 2, is labelled "first even node".

The dashed arrow labelled "joined at the end" finishes the job: node 5 links to node 2, and the list reads 1, 3, 5, 2, 4. So the whole rearrangement is two chains built side by side, plus one link at the end.

Solution Approach

Turning that idea into code means settling three things: how to build both chains in one walk along the list, when that walk stops, and how to join the chains afterwards.

Building both chains in one walk

Why not copy the odd and even values into two Java lists and write them back in order? That works, but those lists grow with the input, and the problem allows only a fixed amount of extra memory. Relinking the nodes needs no copies.

Two markers do the relinking. odd points at the last node of the odd chain so far, and starts at the head. even points at the last node of the even chain so far, and starts at the second node. In each round, the node after even is the next odd node, so odd links to it and moves there. Then the node after the new odd is the next even node, so even links to it and moves there.

On [1, 2, 3, 4, 5], the first round links node 1 to node 3 and node 2 to node 4, leaving odd on 3 and even on 4. The second round links node 3 to node 5, and node 4 to whatever follows node 5, which is nothing. odd ends on 5 and even on nothing, written null in Java.

When the walk stops

When is there no next odd node to link? A round needs an even node and a node after it, so the loop runs while even is not null and even.next is not null. With five nodes the walk stops because even is null. With six nodes it stops on node 6, which has nothing after it.

Either way, odd stops on the last odd node, which is where the even chain must be attached. The even chain also ends cleanly: its last node links to null, so the joined list has a proper end.

Joining the two chains

Where does the even chain start once the walk is over? Its first node is the original second node, but after the first round, node 1 links to node 3, so head.next no longer leads there. The second node has to be saved in a variable, evenHead, before the walk begins. At the end, the last odd node links to evenHead.

Java Solution

The method oddEvenList works in these steps:

  1. First, if head is null, the list is empty and the method returns null.
  2. Set odd to head and even to head.next, and save the first even node in evenHead.
  3. A while loop runs while even and even.next are both not null. Inside, odd.next = even.next links the odd chain to the next odd node, and odd moves there. Then even.next = odd.next links the even chain to the next even node, and even moves there.
  4. After the loop, odd.next = evenHead attaches the even chain to the end of the odd chain, and the method returns head, which is still the first node.

Besides the method, the class has a small ListNode class for the nodes, build to make a list from values, and show to print a list as [1, 3, 5]. The main method runs both examples, a list of six nodes, lists of two nodes and one node, and an empty list.

Java
public class OddEvenLinkedList {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static ListNode oddEvenList(ListNode head) {
        if (head == null) {
            return null;                    // empty list: nothing to move
        }
        ListNode odd = head;                // last node of the odd chain so far
        ListNode even = head.next;          // last node of the even chain so far
        ListNode evenHead = even;           // first even node, joined on at the end
        while (even != null && even.next != null) {
            odd.next = even.next;           // odd jumps over one even node
            odd = odd.next;
            even.next = odd.next;           // even jumps over one odd node
            even = even.next;
        }
        odd.next = evenHead;                // odd chain, then even chain
        return head;
    }

    static ListNode build(int... values) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : values) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static String show(ListNode head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode n = head; n != null; n = n.next) {
            sb.append(n.val).append(n.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(oddEvenList(build(1, 2, 3, 4, 5))));
        System.out.println(show(oddEvenList(build(2, 1, 3, 5, 6, 4, 7))));
        System.out.println(show(oddEvenList(build(1, 2, 3, 4, 5, 6))));
        System.out.println(show(oddEvenList(build(1, 2))));
        System.out.println(show(oddEvenList(build(7))));
        System.out.println(show(oddEvenList(build())));
    }
}

Running it prints:

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

The second line, [2, 3, 6, 7, 1, 5, 4], matches Example 2: the values 1, 5 and 4 are moved back because of where they sit, not because of what they are. The third line shows a list of even length. [1, 2, 3, 4, 5, 6] becomes [1, 3, 5, 2, 4, 6], and the walk stopped with even on node 6, which correctly stays last.

[1, 2] and [7] come back unchanged. With two nodes, even is on node 2 and nothing follows it, so the loop never runs, and odd.next = evenHead links node 1 to node 2 again. With one node, even and evenHead are both null. The last line, [], is the empty list handled by the first check.

The join after the loop must use evenHead, not head.next. After the loop on [1, 2, 3, 4, 5], head.next is node 3. A version ending with odd.next = head.next links node 5 back to node 3, and following the links from the head then gives 1, 3, 5, 3, 5, 3, ... without end.

Complexity

The method walks the list once and changes only links, never creating a node.

  • Time: O(n) for a list of n nodes: each round of the loop moves odd and even two nodes forward, so about n / 2 rounds relink every node once, and the final join is a single step.
  • Space: O(1). The three variables odd, even and evenHead are all the extra memory, whether the list has five nodes or five million.

Splitting a list by value instead of by position is Partition List.