Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order).
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
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 result. c) Move ahead in the list of smaller node. 4) If 'b' becomes NULL before 'a', insert all nodes of 'a' into 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.
List A before merge: 5 10 15 List B before merge: 2 3 20 Merged Linked List is: 20 15 10 5 3 2
This solution traverses both lists only once, doesn’t require reverse and works in-place.
This article is contributed by Mohammed Raqeeb. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Sorted merge of two sorted doubly circular linked lists
- Merge two sorted linked lists
- Merge K sorted linked lists | Set 1
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Merge two sorted linked list without duplicates
- In-place Merge two linked lists without changing links of first list
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Print Doubly Linked list in Reverse Order
- Merge two sorted lists (in-place)
- Merge Sort for Linked Lists
- Merge a linked list into another linked list at alternate positions
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- Insert value in sorted way in a sorted doubly linked list
- Intersection of two Sorted Linked Lists