Given a linked list of integers, rearrange it such that every second node of the linked list is greater than its left and right nodes. In other words, rearrange the linked list node in alternating high-low.

Assume no duplicate nodes are present in the linked list. Several lists might satisfy the constraints; we need to print any one of them. For example,

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

Practice this problem

The idea is to start from the second node in the linked list and advance two nodes in each iteration of the loop. If the previous node is greater than the current node, swap their values. Similarly, if the next node is greater than the current node, exchange both values. At the end of the loop, we will get the desired linked list that satisfies the given constraints.

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

C


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

1 —> 3 —> 2 —> 5 —> 4 —> 7 —> 6 —> 8 —> 6 —> 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.