×

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists

This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists and find the union and intersection of these given two lists. Here we will not consider the order of output list elements.

Example:

Input:

                        List1: 1 -> 8 -> 4 -> 2

                        List2:  3 -> 4 -> 6 -> 2

Output:

                        Intersection of the Lists: 4 -> 2

                        Union of the Lists: 1 -> 8 -> 4 -> 2 -> 3 -> 6

Method:

The following are simple algorithms to get union and intersection lists, respectively.

Intersection (list1, list2):

Firstly, we will initialize the result list with NULL, then we will traverse the list1, and we will check every element in list2. If the elements of the list1 present in the list2, we will add the elements to the resultant list.

Union (list1, list2):

In this section, we will first initialize the result list with NULL. Then, we will traverse the list1 and add all of its elements to the result list. Then, we traverse the list2. If the element of list2 is already present in the result list, we will skip those elements. Else, we will add the rest of its elements to the result list.

C Program to implement the union and intersection of the linked list

 #include<stdio.h>
 #include<stdlib.h>
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start1 = NULL, * start2 = NULL, * res = NULL;
 int len = 0, n;
 // For inserting the elements in the linked list
 void add(int item, struct node **temp)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(*temp == NULL)
 {
 * temp = t;
 (* temp) -> info = item;
 (* temp) -> next = NULL;
 return;
 }
 else
 {
 struct node * p = * temp;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // Function of finding the union of two linked list
 struct node* getUnion(struct node* head1, struct node* head2)
 {
     struct node * result = NULL;
     struct node * t1 = head1, * t2 = head2;
     while (t1 != NULL) {
         add(t1 -> info, &result);
         t1 = t1 -> next;
     }
     while (t2 != NULL) {
         if (!isPresent(result, t2 -> info))
             add(t2 -> info, &result);
         t2 = t2 -> next;
     }
     return result;
 }
 // Function of finding the intersection of two linked list
 struct node * getIntersection(struct node * head1,
                              struct node * head2)
 {
     struct node * result = NULL;
     struct node * t1 = head1;
     while (t1 != NULL) {
         if (isPresent(head2, t1 -> info))
             add(t1-> info,&result);
         t1 = t1-> next;
     }
     return result;
 }
 // Function for checking the elements
 int isPresent(struct node * head, int info)
 {
     struct node * t = head;
     while (t != NULL) {
         if (t -> info == info)
             return 1;
         t = t -> next;
     }
     return 0;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
  if(t == NULL)
 {
             printf(" Linked list is empty\n");
 }
 while(t -> next != NULL)
 {
                         printf("%d -> ", t -> info);
                         t = t -> next;
 }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 // Add element into the linked1
     add(1, &start1);
     add(10, &start1);
     add(3, &start1);
     add(4, &start1);
     add(9, &start1);
     add(8, &start1);
 // Add element into the linked2
     add(1, &start2);
     add(10, &start2);
     add(3, &start2);
     add(6, &start2);
     add(2, &start2);
     add(8, &start2);
     printf("list1: ");
     traverse(start1);
     printf("list2: ");
     traverse(start2);
     res = getUnion(start1, start2);
     printf("Union is: ");
     traverse(res);
     res = getIntersection(start1, start2);
     printf("Intersection is: ");
     traverse(res);
     return 0;
 } 

Output:

Union and Intersection of two Linked Lists

Time Complexity: The time complexity of the above method is O(m*n), where m and n are the numbers of elements present in the first and second linked list, respectively.


Related Topics

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java In this article, we are going to see how to find the intersection point in a Y-shaped linked list. Method 1: We need to...

4 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Function to Delete a Leaf Node from a Binary Tree

Implementation // We are writing a C++ code to eliminate all the leaves from the given value.  #include <bits/stdc++.h> using namespace std; // creating a new binary tree node struct __nod { int record; struct __nod *Lft,...

4 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique...

3 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Huffman tree in Data Structures

The Huffman trees in the field of data structures are pretty impressive in their work. They are generally treated as the binary tree, which is linked with the least external...

6 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.