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
Output: [1, 3, 5, 2, 4]
Example 2
Output: [2, 3, 6, 7, 1, 5, 4]
Explanation: the positions decide the groups, not the values.
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 nextnext
Example 2 shows that only positions count. In [2, 1, 3, 5, 6, 4, 7]
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
Look at the list [1, 2, 3, 4, 5]
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. oddevenevenoddoddeven
On [1, 2, 3, 4, 5]oddevenoddevennull
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 evennulleven.nextnullevennull
Either way, oddnull
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.nextevenHeadevenHead
Java Solution
The method oddEvenList
- First, if
ishead , the list is empty and the method returnsnull .null - Set
toodd andhead toeven , and save the first even node inhead.next .evenHead - A
loop runs whilewhile andeven are both noteven.next . Inside,null links the odd chain to the next odd node, andodd.next = even.next moves there. Thenodd links the even chain to the next even node, andeven.next = odd.next moves there.even - After the loop,
attaches the even chain to the end of the odd chain, and the method returnsodd.next = evenHead , which is still the first node.head
Besides the method, the class has a small ListNodebuildshow[1, 3, 5]main
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:
[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][1, 2, 3, 4, 5, 6][1, 3, 5, 2, 4, 6]even
[1, 2][7]evenodd.next = evenHeadevenevenHeadnull[]
The join after the loop must use evenHeadhead.next[1, 2, 3, 4, 5]head.nextodd.next = head.next
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
andodd two nodes forward, so about n / 2 rounds relink every node once, and the final join is a single step.even - Space: O(1). The three variables
,odd andeven are all the extra memory, whether the list has five nodes or five million.evenHead
Splitting a list by value instead of by position is