Union and Intersection of two Linked Lists

Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. Order of elments in output lists doesn’t matter.

Example:

```Input:
List1: 10->15->4->20
lsit2:  8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
```

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Method 1 (Simple)
Following are simple algorithms to get union and intersection lists respectively.

Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the element is present in list2, then add the element to result.

Union (list1, list2):
Initialize result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in result then do not insert it to result, otherwise insert.

This method assumes that there are no duplicates in the given lists.

Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method.

C/C++

```// C/C++ program to find union and intersection of two unsorted
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct Node
{
int data;
struct Node* next;
};

/* A utility function to insert a node at the beginning of
void push(struct Node** head_ref, int new_data);

/* A utility function to check if given data is present in a list */
bool isPresent(struct Node *head, int data);

{
struct Node *result = NULL;

// Insert all elements of list1 to the result list
while (t1 != NULL)
{
push(&result, t1->data);
t1 = t1->next;
}

// Insert those elements of list2 which are not
// present in result list
while (t2 != NULL)
{
if (!isPresent(result, t2->data))
push(&result, t2->data);
t2 = t2->next;
}

return result;
}

/* Function to get intersection of two linked lists
{
struct Node *result = NULL;

// 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)
{
push (&result, t1->data);
t1 = t1->next;
}

return result;
}

/* A utility function to insert a node at the begining of a linked list*/
void push (struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* A utility function to print a linked list*/
void printList (struct Node *node)
{
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
}

/* A utility function that returns true if data is
present in linked list else return false */
bool isPresent (struct Node *head, int data)
{
while (t != NULL)
{
if (t->data == data)
return 1;
t = t->next;
}
return 0;
}

/* Drier program to test above function*/
int main()
{
struct Node* intersecn = NULL;
struct Node* unin = NULL;

/*create a linked lits 10->15->5->20 */

/*create a linked lits 8->4->2->10 */

printf ("\n First list is \n");

printf ("\n Second list is \n");

printf ("\n Intersection list is \n");
printList (intersecn);

printf ("\n Union list is \n");
printList (unin);

return 0;
}
```

Java

```// Java program to find union and intersection of two unsorted
{

class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

/* Function to get Union of 2 Linked Lists */
{

//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)
{
push(t2.data);
t2 = t2.next;
}
}

{
Node result = null;

// 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)
{
push(t1.data);
t1 = t1.next;
}
}

/* Utility function to print list */
void printList()
{
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 */

/* 4. Move the head to point to new Node */
}

/* A utilty function that returns true if data is present
in linked list  else return false */
boolean isPresent (Node head, int data)
{
while (t != null)
{
if (t.data == data)
return true;
t = t.next;
}
return false;
}

/* Drier program to test above functions */
public static void main(String args[])
{

/*create a linked lits 10->15->5->20 */
llist1.push(20);
llist1.push(4);
llist1.push(15);
llist1.push(10);

/*create a linked lits 8->4->2->10 */
llist2.push(10);
llist2.push(2);
llist2.push(4);
llist2.push(8);

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
```

Time Complexity: O(mn) for both union and intersection operations. Here m is the number of elements in first list and n is the number of elements in second list.

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.
Following are the steps to be followed to get union and intersection lists.

1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.
3) 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.

Time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.

Method 3 (Use Hashing)
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 the element in hash table. If the element is not present, then insert the element to result list. If the element is present, then ignore it.

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 hash table. Traverse list2, for each element being visited in list2, look the element in hash table. If the element is present, then insert the element to result list. If the element is not present, then ignore it.

Both of the above methods assume that there are no duplicates.

```// Java code for Union and Intersection of two
import java.util.HashMap;
import java.util.HashSet;

class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

/* Utility function to print list */
void printList()
{
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 */

/* 4. Move the head to point to new Node */
}

public void append(int new_data)
{
{
Node n = new Node(new_data);
return;
}
Node n2 = new Node(new_data);
while(n1.next != null)
{
n1 = n1.next;
}

n1.next = n2;
n2.next = null;
}

/* A utilty function that returns true if data is
present in linked list else return false */
boolean isPresent (Node head, int data)
{
while (t != null)
{
if (t.data == data)
return true;
t = t.next;
}
return false;
}

{
HashSet<Integer> hset = new HashSet<>();

// loop stores all the elements of list1 in hset
while(n1 != null)
{
if(hset.contains(n1.data))
{
}
else
{
}
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;
}

{
// HashMap that will store the
// elements of the lists with their counts
HashMap<Integer, Integer> hmap = new HashMap<>();

// 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[])
{

/*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);

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
```

Time complexity of this method depends on the hashing technique used and the distribution of elements in input lists. In practical, this approach may turn out to be better than above 2 methods.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
2.5 Average Difficulty : 2.5/5.0
Based on 143 vote(s)