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.