Write a function that takes two lists, each of which is sorted in increasing order, and merges the two into one list, which is in decreasing order, and returns it. In other words, merge two sorted linked lists from their end.

For example, consider lists a = {1, 3, 5} and b = {2, 6, 7, 10}. Merging both lists should yield the list {10, 7, 6, 5, 3, 2, 1}.

Practice this problem

There are few cases to deal with – either a or b may be empty, during processing, either a or b may run out first, and finally, there’s the problem of starting the result list empty, and building it up while going through a and b.

 
We can easily solve this problem using the moveNode() function as a helper, which takes the node from the front of the source and moves it to the front of the destination. The rest of the code remains similar to the merge process of merge sort.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

First List: 2 —> 4 —> 6 —> NULL
Second List: 1 —> 3 —> 5 —> 7 —> 9 —> NULL
 
After Merge: 9 —> 7 —> 6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

Java


Download  Run Code

Output:

First List: 2 —> 4 —> 6 —> null
Second List: 1 —> 3 —> 5 —> 7 —> 9 —> null
 
After Merge: 9 —> 7 —> 6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Python


Download  Run Code

Output:

First List: 2 —> 4 —> 6 —> None
Second List: 1 —> 3 —> 5 —> 7 —> 9 —> None
 
After Merge: 9 —> 7 —> 6 —> 5 —> 4 —> 3 —> 2 —> 1 —> 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.