Saturday, December 28, 2024
Google search engine
HomeData Modelling & AIC++ Program For Merging Two Sorted Linked Lists Such That Merged List...

C++ Program For Merging Two Sorted Linked Lists Such That Merged List Is In Reverse Order

Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order).

Examples: 

Input:  a: 5->10->15->40
        b: 2->3->20 
Output: res: 40->20->15->10->5->3->2

Input:  a: NULL
        b: 2->3->20 
Output: res: 20->3->2

A Simple Solution is to do following. 
1) Reverse first list ‘a’
2) Reverse second list ‘b’
3) Merge two reversed lists.
Another Simple Solution is first Merge both lists, then reverse the merged list.
Both of the above solutions require two traversals of linked list. 

How to solve without reverse, O(1) auxiliary space (in-place) and only one traversal of both lists? 
The idea is to follow merge style process. Initialize result list as empty. Traverse both lists from beginning to end. Compare current nodes of both lists and insert smaller of two at the beginning of the result list. 

1) Initialize result list as empty: res = NULL.
2) Let 'a' and 'b' be heads first and second lists respectively.
3) While (a != NULL and b != NULL)
    a) Find the smaller of two (Current 'a' and 'b')
    b) Insert the smaller value node at the front of the result.
    c) Move ahead in the list of the smaller nodes. 
4) If 'b' becomes NULL before 'a', insert all nodes of 'a' 
   into the result list at the beginning.
5) If 'a' becomes NULL before 'b', insert all nodes of 'a' 
   into result list at the beginning. 

Below is the implementation of above solution.

C++14





Output: 

List A before merge: 
5 10 15 
List B before merge: 
2 3 20 
Merged Linked List is: 
20 15 10 5 3 2 

Time Complexity: O(N)

Auxiliary Space: O(1)

This solution traverses both lists only once, doesn’t require reverse and works in-place.

 

Please refer complete article on Merge two sorted linked lists such that merged list is in reverse order for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
22 Mar, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments