Merge two sorted linked lists such that merged list is in reverse order - GeeksforGeeks
Merge 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
We strongly recommend you to minimize your browser and try this yourself first.
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.
Read full article from Merge two sorted linked lists such that merged list is in reverse order - GeeksforGeeks
No comments:
Post a Comment