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).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Merge K sorted Doubly Linked List in Sorted Order
- Merge two sorted linked lists
- Merge two sorted linked lists such that merged list is in reverse order
- Merge two unsorted linked lists to get a sorted list
- Merge K sorted linked lists | Set 1
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Find count of common nodes in two Doubly Linked Lists
- Doubly Circular Linked List | Set 1 (Introduction and Insertion)
- Doubly Circular Linked List | Set 2 (Deletion)
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Insertion at Specific Position in a Circular Doubly Linked List
- Convert an Array to a Circular Doubly Linked List
- Reverse a doubly circular linked list
- Search an Element in Doubly Circular Linked List
- Remove all even parity nodes from a Doubly and Circular Singly Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- In-place Merge two linked lists without changing links of first list
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- Difference of two Linked Lists using Merge sort
- Merge odd and even positioned nodes of two Linked Lists alternately
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.