Given two sorted Doubly circular Linked List containing n1 and n2 nodes respectively. The problem is to merge the two lists such that resultant list is also in sorted order.
Approach: Following are the steps:
- If head1 == NULL, return head2.
- If head2 == NULL, return head1.
- Let last1 and last2 be the last nodes of the two lists respectively. They can be obtained with the help of the previous links of the first nodes.
- Get pointer to the node which will be the last node of the final list. If last1.data < last2.data, then last_node = last2, Else last_node = last1.
- Update last1.next = last2.next = NULL.
- Now merge the two lists as two sorted doubly linked list are being merged. Refer merge procedure of this post. Let the first node of the final list be finalHead.
- Update finalHead.prev = last_node and last_node.next = finalHead.
- Return finalHead.
Final Sorted List: 1 2 3 5 7 8 9 11
Time Complexity: O(n1 + n2).
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Merge K sorted Doubly Linked List in Sorted Order
- Merge K sorted linked lists | Set 1
- Merge two sorted linked lists
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Merge two unsorted linked lists to get a sorted list
- Merge two sorted linked lists such that merged list is in reverse order
- Insert value in sorted way in a sorted doubly linked list
- Merge two sorted lists (in-place)
- Sort a k sorted doubly linked list
- Remove duplicates from a sorted doubly linked list
- Merge two sorted linked list without duplicates
- Sorted insert for circular linked list
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Find pairs with given product in a sorted Doubly Linked List
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Intersection of two Sorted Linked Lists
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Sorted insert in a doubly linked list with head and tail pointers
- Insertion in a sorted circular linked list when a random pointer is given
- Given a linked list which is sorted, how will you insert in sorted way
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.