Java Program To Perform Union of Two Linked Lists Using Priority Queue
Last Updated :
30 May, 2022
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
Approach:
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
- Removal
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.
Example
Java
// JAva Program toIllustrate Union of Two Linked Lists
// Using Priority Queue
// Importing basic required classes
import java.io.*;
import java.util.*;
// Class 1
// Helper class
// Node creation
class Node {
// Data and addressing variable of node
int data;
Node next;
// Constructor to initialize node
Node(int a)
{
data = a;
next = null;
}
}
// Class 2
// Main class
public class GfG {
// Reading input via Scanner class
static Scanner sc = new Scanner(System.in);
// Method 1
// To create the input list1
public static Node inputList1()
{
// Declaring node variables that is
// Head and tail
Node head, tail;
// Custom input node elements
head = tail = new Node(9);
tail.next = new Node(6);
// Fetching for next node
// using next() method
tail = tail.next;
// Similarly for node 3
tail.next = new Node(4);
tail = tail.next;
// Similarly for node 4
tail.next = new Node(2);
tail = tail.next;
// Similarly for node 5
tail.next = new Node(3);
tail = tail.next;
// Similarly for node 6
tail.next = new Node(8);
tail = tail.next;
// Returning the head
return head;
}
// Method 2
// To create the input List2
// Similar to method 1 but for List2
public static Node inputList2()
{
Node head, tail;
head = tail = new Node(1);
tail.next = new Node(2);
tail = tail.next;
tail.next = new Node(8);
tail = tail.next;
tail.next = new Node(6);
tail = tail.next;
tail.next = new Node(2);
tail = tail.next;
return head;
}
// Method 3
// To print the union list
public static void printList(Node n)
{
// Till there is a node
// condition holds true
while (n != null) {
// Print the node
System.out.print(n.data + " ");
// Moving onto next node
n = n.next;
}
}
// Method 4
// main driver method
public static void main(String args[])
{
// Taking input for List 1 and List 2
Node head1 = inputList1();
Node head2 = inputList2();
// Calling
Union obj = new Union();
printList(obj.findUnion(head1, head2));
}
}
// Class 3
// To make the union of two linked list
class Union {
public static Node findUnion(Node head1, Node head2)
{
// Creating a priority queue where
// declaring elements of integer type
PriorityQueue<Integer> minheap
= new PriorityQueue<Integer>();
// Setting heads
Node l1 = head1, l2 = head2;
// For List 1
// Inserting elements from linked list1 into
// priority queue
while (l1 != null) {
if (!minheap.contains(l1.data)) {
minheap.add(l1.data);
}
// Move to next element
l1 = l1.next;
}
// For List 2
// Inserting elements from linked list2 into
// priority queue
while (l2 != null) {
if (!minheap.contains(l2.data)) {
minheap.add(l2.data);
}
// Move to next element
l2 = l2.next;
}
Node union = new Node(0), start = union;
// Removing until heap is empty
while (!minheap.isEmpty()) {
Node temp = new Node(minheap.remove());
// Using temp to store start
start.next = temp;
start = start.next;
}
// Returning node
return union.next;
}
}
Time complexity: O(nlogn), Space complexity: O(n)
Similar Reads
Java Program To Merge K Sorted Linked Lists Using Min Heap - Set 2 Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples: Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL l
5 min read
Java Program to Merge Two Sorted Linked Lists in New List We are given two sorted List and our goal is to merge these two lists into a new list. For that, we have to write one function which will take two List as an argument which is sorted in increasing order. This function will Merge these two List into one List in increasing order. Input List 1 : 1->
4 min read
Java Program For Union And Intersection Of Two Linked Lists Write a java program for a given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn't matter.Example: Input:List1: 10->15->4->20List2: 8->4->2->10Output:In
10 min read
Java Program To Merge K Sorted Linked Lists - Set 1 Given K sorted linked lists of size N each, merge them and print the sorted output. Examples:Â Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL list3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->7->8->9->10->11 Merged lists in a sorted order where every element is greater t
6 min read
How to Find the Intersection and Union of Two PriorityQueues in Java? In Java, PriorityQueue is an implementation of the Queue Interface. It can be used to provide a way to store the elements in a queue based on their priority basis. This means high-priority elements can store first compared to lower-priority elements in the queue. In this article, we will be learning
2 min read
Java Program For Finding Intersection Point Of Two Linked Lists There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists havi
7 min read
How to Perform Range Queries on a PriorityQueue in Java? Based on a priority heap, a Java PriorityQueue represents an unlimited priority queue. PriorityQueue does not directly handle range queries, but it does provide quick access to the element with the greatest priority. On the other hand, range queries may be executed by taking pieces from the Priority
2 min read
Java Program To Merge Two Sorted Lists (In-Place) Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: T
5 min read
Java Program to Implement Triply Linked List Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. In this post, methods to insert a new node in a linked list are discussed. A node can be inserted in three ways either at the front of the linked list or after a given node or at the
8 min read
Java Program For Finding Intersection Of Two Sorted Linked Lists Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2-
5 min read