×

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

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.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because...

6 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

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

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

8 minutes read.

Partitioning a linked list around a given value

Partitioning a linked list around a given value In this problem, we are given a linked list and a value k. We need to partition the given linked list so that...

3 minutes read.

Deletion in Binary Search Tree

Implementation #include <iostream> using namespace std; struct _nod {   int ky;   struct _nod *Lft, *Rt; }; // Creating a node in the binary tree. struct _nod *nw_nod(int Itm) {   struct _nod *temp = (struct _nod *)malloc(sizeof(struct...

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.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Given a Binary Tree, find its Minimum Depth

Implementation // Creating a C++ program or implementation to search and explore the minimum depth of a given binary tree.  #include<bits/stdc++.h> using namespace std; // Creating a new binary tree node struct __nod { int record; struct __nod*...

5 minutes read.

Introduction to 2D-Arrays

Two Dimensional Array Technical Definitions An array of arrays is a common definition for a two-dimensional array. A matrix is another name for a two-dimensional array. A matrix looks like a table...

3 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.

Difference between Structured and Object-Oriented Analysis

Analysis means observing and collecting relevant information about the structure of something or the basic details of a system's requirements. Structured and Object Oriented Analysis are both widely used in...

2 minutes read.