Given a linked list, rearrange its nodes such that alternate positions are filled with nodes starting from the beginning and end of the list. in linear time and constant space.

For example,

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

Practice this problem

We can easily solve this problem by dividing it into three subproblems:

  • Divide the list into two equal parts.
  • Reverse the second half.
  • Merge the second half into the first half at alternate positions. Use of extra space is not allowed (Not allowed to create additional nodes), i.e., insertion must be done in-place.

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

C


Download  Run Code

Output:

1 —> 6 —> 2 —> 5 —> 3 —> 4 —> NULL

Java


Download  Run Code

Output:

1 —> 6 —> 2 —> 5 —> 3 —> 4 —> null

Python


Download  Run Code

Output:

1 —> 6 —> 2 —> 5 —> 3 —> 4 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.