Java Program For Union And Intersection Of Two Linked Lists
Last Updated :
12 Oct, 2023
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->20
List2: 8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Method 1 (Simple):
The following are simple algorithms to get union and intersection lists respectively.
Intersection (list1, list2)
Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.
Union (list1, list2):
Initialize a new list ans and store first and second list data to set to remove duplicate data
and then store it into our new list ans and return its head.
Below is the implementation of above approach:
Java
// Java program to find union and
// intersection of two unsorted
// linked lists
class LinkedList {
Node head; // head of list
/* Linked list Node*/
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Function to get Union of 2 Linked Lists */
void getUnion(Node head1, Node head2)
{
Node t1 = head1, t2 = head2;
// insert all elements of list1 in the result
while (t1 != null) {
push(t1.data);
t1 = t1.next;
}
// insert those elements of list2
// that are not present
while (t2 != null) {
if (!isPresent(head, t2.data))
push(t2.data);
t2 = t2.next;
}
}
void getIntersection(Node head1, Node head2)
{
Node result = null;
Node t1 = head1;
// Traverse list1 and search each
// element of it in list2.
// If the element is present in
// list 2, then insert the
// element to result
while (t1 != null) {
if (isPresent(head2, t1.data))
push(t1.data);
t1 = t1.next;
}
}
/* Utility function to print list */
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
/* Inserts a node at start of linked list */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* A utility function that returns true
if data is present in linked list
else return false */
boolean isPresent(Node head, int data)
{
Node t = head;
while (t != null) {
if (t.data == data)
return true;
t = t.next;
}
return false;
}
/* Driver program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
LinkedList unin = new LinkedList();
LinkedList intersecn = new LinkedList();
/*create a linked lists 10->15->4->20 */
llist1.push(20);
llist1.push(4);
llist1.push(15);
llist1.push(10);
/*create a linked lists 8->4->2->10 */
llist2.push(10);
llist2.push(2);
llist2.push(4);
llist2.push(8);
intersecn.getIntersection(llist1.head, llist2.head);
unin.getUnion(llist1.head, llist2.head);
System.out.println("First List is");
llist1.printList();
System.out.println("Second List is");
llist2.printList();
System.out.println("Intersection List is");
intersecn.printList();
System.out.println("Union List is");
unin.printList();
}
} /* This code is contributed by Rajat Mishra */
Output:
First list is
10 15 4 20
Second list is
8 4 2 10
Intersection list is
4 10
Union list is
2 8 20 4 15 10
Complexity Analysis:
- Time Complexity: O(m*n).
Here 'm' and 'n' are number of elements present in the first and second lists respectively.
For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.
For intersection: For every element in list-1 we check if that element is also present in list-2. - Auxiliary Space: O(1).
No use of any data structure for storing values.
Method 2 (Use Merge Sort):
In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection.
The following are the steps to be followed to get union and intersection lists.
- Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.
- Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.
- Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here.
Below is the implementation of above approach:
Java
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
public class LinkedListUnion {
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// function to print linked list
public static void printLinkedList(Node head)
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + "-->");
temp = temp.next;
}
System.out.print("None");
}
// function to get union of two linked lists
static Node getUnion(Node ll1, Node ll2)
{
Node tail = null;
Node head = null;
while (ll1 != null || ll2 != null) {
if (ll1 == null) {
if (tail == null) {
tail = new Node(ll2.data);
head = tail;
}
else {
tail.next = new Node(ll2.data);
tail = tail.next;
}
ll2 = ll2.next;
}
else if (ll2 == null) {
if (tail == null) {
tail = new Node(ll1.data);
head = tail;
}
else {
tail.next = new Node(ll1.data);
tail = tail.next;
}
ll1 = ll1.next;
}
else {
if (ll1.data < ll2.data) {
if (tail == null) {
tail = new Node(ll1.data);
head = tail;
}
else {
tail.next = new Node(ll1.data);
tail = tail.next;
}
ll1 = ll1.next;
}
else if (ll1.data > ll2.data) {
if (tail == null) {
tail = new Node(ll2.data);
head = tail;
}
else {
tail.next = new Node(ll2.data);
tail = tail.next;
}
ll2 = ll2.next;
}
else {
if (tail == null) {
tail = new Node(ll1.data);
head = tail;
}
else {
tail.next = new Node(ll1.data);
tail = tail.next;
}
ll1 = ll1.next;
ll2 = ll2.next;
}
}
}
return head;
}
// main function to test the code
public static void main(String[] args)
{
// create first linked list
Node head1 = new Node(10);
head1.next = new Node(20);
head1.next.next = new Node(30);
head1.next.next.next = new Node(40);
head1.next.next.next.next = new Node(50);
head1.next.next.next.next.next = new Node(60);
head1.next.next.next.next.next.next = new Node(70);
// create second linked list
Node head2 = new Node(10);
head2.next = new Node(30);
head2.next.next = new Node(50);
head2.next.next.next = new Node(80);
head2.next.next.next.next = new Node(90);
Node head = getUnion(head1, head2);
printLinkedList(head);
System.out.println();
}
}
// This code is contributed by Vikram_Shirsat
Output10-->20-->30-->40-->50-->60-->70-->80-->90-->None
Method 3 (Use Hashing):
1. Union (list1, list2):
Initialize the result list as NULL and create an empty hash table. Traverse both lists one by one, for each element being visited, look at the element in the hash table. If the element is not present, then insert the element into the result list. If the element is present, then ignore it.
2. Intersection (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse list1. For each element being visited in list1, insert the element in the hash table. Traverse list2, for each element being visited in list2, look the element in the hash table. If the element is present, then insert the element to the result list. If the element is not present, then ignore it.
Both of the above methods assume that there are no duplicates.
Below is the implementation of above approach:
Java
// Java code for Union and Intersection of two
// Linked Lists
import java.util.HashMap;
import java.util.HashSet;
class LinkedList {
Node head; // head of list
/* Linked list Node*/
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Utility function to print list */
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
/* Inserts a node at start of linked list */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
public void append(int new_data)
{
if (this.head == null) {
Node n = new Node(new_data);
this.head = n;
return;
}
Node n1 = this.head;
Node n2 = new Node(new_data);
while (n1.next != null) {
n1 = n1.next;
}
n1.next = n2;
n2.next = null;
}
/* A utility function that returns true if data is
present in linked list else return false */
boolean isPresent(Node head, int data)
{
Node t = head;
while (t != null) {
if (t.data == data)
return true;
t = t.next;
}
return false;
}
LinkedList getIntersection(Node head1, Node head2)
{
HashSet<Integer> hset = new HashSet<>();
Node n1 = head1;
Node n2 = head2;
LinkedList result = new LinkedList();
// loop stores all the elements of list1 in hset
while (n1 != null) {
if (hset.contains(n1.data)) {
hset.add(n1.data);
}
else {
hset.add(n1.data);
}
n1 = n1.next;
}
// For every element of list2 present in hset
// loop inserts the element into the result
while (n2 != null) {
if (hset.contains(n2.data)) {
result.push(n2.data);
}
n2 = n2.next;
}
return result;
}
LinkedList getUnion(Node head1, Node head2)
{
// HashMap that will store the
// elements of the lists with their counts
HashMap<Integer, Integer> hmap = new HashMap<>();
Node n1 = head1;
Node n2 = head2;
LinkedList result = new LinkedList();
// loop inserts the elements and the count of
// that element of list1 into the hmap
while (n1 != null) {
if (hmap.containsKey(n1.data)) {
int val = hmap.get(n1.data);
hmap.put(n1.data, val + 1);
}
else {
hmap.put(n1.data, 1);
}
n1 = n1.next;
}
// loop further adds the elements of list2 with
// their counts into the hmap
while (n2 != null) {
if (hmap.containsKey(n2.data)) {
int val = hmap.get(n2.data);
hmap.put(n2.data, val + 1);
}
else {
hmap.put(n2.data, 1);
}
n2 = n2.next;
}
// Eventually add all the elements
// into the result that are present in the hmap
for (int a : hmap.keySet()) {
result.append(a);
}
return result;
}
/* Driver program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
LinkedList union = new LinkedList();
LinkedList intersection = new LinkedList();
/*create a linked list 10->15->4->20 */
llist1.push(20);
llist1.push(4);
llist1.push(15);
llist1.push(10);
/*create a linked list 8->4->2->10 */
llist2.push(10);
llist2.push(2);
llist2.push(4);
llist2.push(8);
intersection = intersection.getIntersection(
llist1.head, llist2.head);
union = union.getUnion(llist1.head, llist2.head);
System.out.println("First List is");
llist1.printList();
System.out.println("Second List is");
llist2.printList();
System.out.println("Intersection List is");
intersection.printList();
System.out.println("Union List is");
union.printList();
}
}
// This code is contributed by Kamal Rawal
Output:
First List is
10 15 4 20
Second List is
8 4 2 10
Intersection List is
10 4
Union List is
2 4 20 8 10 15
Complexity Analysis:
- Time Complexity: O(m+n).
Here 'm' and 'n' are number of elements present in the first and second lists respectively.
For union: Traverse both the lists, store the elements in Hash-map and update the respective count.
For intersection: First traverse list-1, store its elements in Hash-map and then for every element in list-2 check if it is already present in the map. This takes O(1) time. - Auxiliary Space:O(m+n).
Use of Hash-map data structure for storing values.
Please refer complete article on Union and Intersection of two Linked Lists for more details!
Similar Reads
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
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
Java Program For Inserting A Node In A Linked List
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. Java // Linked List Class class LinkedList { // Head of list Node
7 min read
Java Program to Get Elements of a LinkedList
Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList. 1. We can use get(int variable) method to access an element from a specific index of LinkedList: In the given example, we have used
4 min read
Java Program To Check If Two Linked Lists Are Identical
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE
3 min read
Java Program To Delete Middle Of Linked List
Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
4 min read
Java Program to Implement LinkedList API
Linked List is a part of the Collection framework That is present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure in which the elements are not stored in contiguous locations and every element is a separate object with a data pa
10 min read
Java Program to Get the First and the Last Element of a Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The given task is to retrieve the first and the last element of a given linked list. Properties of a Linked ListElements are stored in a non-contiguous manner.Every element is an object whi
4 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 to Search an Element in a Linked List
Prerequisite: LinkedList in java LinkedList is a linear data structure where the elements are not stored in contiguous memory locations. Every element is a separate object known as a node with a data part and an address part. The elements are linked using pointers or references. Linked Lists are pre
5 min read