Java Program To Perform Union of Two Linked Lists Using Priority Queue
Given two linked lists, your task is to complete the function make union(), which returns the union of two linked lists. This union should include all the distinct elements only. The new list formed should be in non-decreasing order.
Input: L1 = 9->6->4->2->3->8 L2 = 1->2->8->6->2 Output: 1 2 3 4 6 8 9
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
There are two types of heap as we all know that is min heap and max heap
- Min heap – Stores all the elements in ascending order
- Max heap – Stores all the elements in descending order
Let us first visualize using min heap in order to interpret program execution how union of two linked list is carried on, so de we are having two operations as listed to visualize:
Insertion: After inserting all the distinct elements of two linked lists,
Removal: Removing the root until minheap is empty
Removing the root with value 1:
Removing the root with value 2:
Removing the root with value 3:
Removing the root with value 4:
Removing the root with value 6:
Removing the root with value 8:
Removing the root with value 9:
Hence we can conclude that in the min-heap, the smallest element will be at the root of the heap, and in the max heap, the greatest element will be at the root of the heap. While implementing the remove() function on heap, the root element will be removed. Since the output should be in increasing order, Min heap can be used. Priority Queue is used to implement min heap in java.
1 2 3 4 6 8 9
Time complexity: O(nlogn), Space complexity: O(n)