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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read