Rearrange a given linked list such that every even node will be moved to the end of the list in reverse order.

For example,

Input:  1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> null
 
Output: 1 —> 3 —> 5 —> 7 —> 6 —> 4 —> 2 —> null

Practice this problem

The idea is to use the moveNode() function. The function takes a node from the front of the source and moves it to the destination’s front. Here, the source node will be even nodes in the given list, and the destination will be a new list. After we have moved every even node, append the new list, which now contains the even nodes in reverse order to the original list.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Before: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> NULL
After: 1 —> 3 —> 5 —> 7 —> 6 —> 4 —> 2 —> NULL

Java


Download  Run Code

Output:

Before: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> null
After: 1 —> 3 —> 5 —> 7 —> 6 —> 4 —> 2 —> null

Python


Download  Run Code

Output:

Before: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> None
After: 1 —> 3 —> 5 —> 7 —> 6 —> 4 —> 2 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list. The auxiliary space required by the program is constant.