Given a linked list, rearrange it by separating odd nodes from even ones. All even nodes should come before all odd nodes in the output list, and the relative order of even and odd nodes should be maintained.

For example, consider list {1, 2, 3, 4, 5, 6, 7}. Rearranging it should yield {2, 4, 6, 1, 3, 5, 7}.

Practice this problem

1. Using Iteration

The problem can be solved either iteratively or recursively. Following is the simple iterative implementation in C, Java, and Python that does not use a dummy node:

C


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> NULL

Java


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> null

Python


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> None

2. Using Dummy Nodes

We can simplify the above code by using two temporary dummy nodes as the odd and even list and maintaining two pointers that always point to the last node in individual lists, so appending new nodes is easy. The dummy node gives the tail something to point to initially when the result list is empty. This dummy node is efficient since it is only temporary, and it is allocated in the stack. The loop proceeds, removing nodes from the original list and adding it at the tail of the even or odd list. When we are done, rearrange the pointers so that all odd nodes follow all even nodes.

Following is the C, Java, and Python implementation of the idea:

C


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> NULL

Java


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> null

Python


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> None

3. Using Recursion

This is one of those excellent problems where the recursive solution code is much cleaner than the iterative code. The recursive implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> NULL

Java


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> null

Python


Download  Run Code

Output:

2 —> 4 —> 6 —> 8 —> 10 —> 1 —> 3 —> 5 —> 7 —> 9 —> None

The time complexity of all above-discussed methods is O(n), where n is the length of the linked list. The iterative version doesn’t require any extra space, whereas the recursive version uses stack space proportional to the lists’ length.

 
Exercise: Modify the solution so that all odd nodes comes before all even nodes.