×

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

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

FIFO approach

FIFO is first in first out approach. It is done for the list of elements in data structures where first element will be deleted after another element ia added to it Here,...

6 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 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.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

Finding the Minimum and Maximum Value of a Binary Tree

Implementation // Writing a C++ program that will help us find out the maximum and the minimum in a binary tree.  #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new class tree node. class...

5 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 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.

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

6 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.