Open In App

C++ Program For Union And Intersection Of Two Linked Lists

Last Updated : 12 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a C++ 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:

C++




// C++ program to find union
// and intersection of two unsorted
// linked lists
#include "bits/stdc++.h"
using namespace std;
 
/* Linked list node */
struct Node {
    int data;
    struct Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
/* A utility function to insert a
node at the beginning ofa linked list*/
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);
 
/* Function to get union of two
linked lists head1 and head2 */
struct Node* getUnion(struct Node* head1,
                      struct Node* head2)
{
    struct Node* ans = new Node(-1);
    struct Node* head = ans;
    set<int> st;
    while (head1 != NULL) {
        st.insert(head1->data);
        head1 = head1->next;
    }
    while (head2 != NULL) {
        st.insert(head2->data);
        head2 = head2->next;
    }
    for (auto it : st) {
        struct Node* t = new Node(it);
        ans->next = t;
        ans = ans->next;
    }
    head = head->next;
    return head;
}
 
/* Function to get intersection of
two linked lists head1 and head2 */
struct Node* getIntersection(struct Node* head1,
                             struct Node* head2)
{
 
    struct Node* result = NULL;
    struct 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(&result, t1->data);
        t1 = t1->next;
    }
    return result;
}
/* A utility function to insert a
node at the beginning 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 of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* A utility function to print a linked list*/
void printList(struct Node* node)
{
    while (node != NULL) {
        cout << " " << node->data;
        node = node->next;
    }
}
bool isPresent(struct Node* head, int data)
{
    struct Node* t = head;
    while (t != NULL) {
        if (t->data == data)
            return 1;
        t = t->next;
    }
    return 0;
}
 
/* Driver program to test above function*/
int main()
{
 
    /* Start with the empty list */
    struct Node* head1 = NULL;
    struct Node* head2 = NULL;
    struct Node* intersecn = NULL;
    struct Node* unin = NULL;
 
    /*create a linked lists 10->15->5->20 */
    push(&head1, 20);
    push(&head1, 4);
    push(&head1, 15);
    push(&head1, 10);
 
    /*create a linked lists 8->4->2->10 */
    push(&head2, 10);
    push(&head2, 2);
    push(&head2, 4);
    push(&head2, 8);
    intersecn = getIntersection(head1, head2);
    unin = getUnion(head1, head2);
    cout << "\n First list is " << endl;
    printList(head1);
    cout << "\n Second list is " << endl;
    printList(head2);
    cout << "\n Intersection list is " << endl;
    printList(intersecn);
    cout << "\n Union list is " << endl;
    printList(unin);
    return 0;
}
 
// This code is contributed by zishanahmad786


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.

Below is the implementation of above approach:

C++




#include <iostream>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
 
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
 
// function to print linked list
void printLinkedList(Node* head)
{
    Node* temp = head;
    while (temp != NULL) {
        cout << temp->data << "-->";
        temp = temp->next;
    }
    cout << "None";
}
 
// function to get union of two linked lists
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
int main()
{
    // 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);
    cout << endl;
 
    return 0;
}
 
// This code is contributed by Gaurav


Output

10-->20-->30-->40-->50-->60-->70-->80-->90-->None


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

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:

C++




#include <iostream>
#include <map>
#include <unordered_set>
using namespace std;
 
class LinkedList {
public:
    struct Node {
        int data;
        Node* next;
        Node(int d)
            : data(d)
            , next(nullptr)
        {
        }
    };
    Node* head = nullptr;
 
    void printList()
    {
        Node* temp = head;
        while (temp != nullptr) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
 
    void push(int new_data)
    {
        Node* new_node = new Node(new_data);
        new_node->next = head;
        head = new_node;
    }
 
    void append(int new_data)
    {
        if (head == nullptr) {
            Node* n = new Node(new_data);
            head = n;
            return;
        }
        Node* n1 = head;
        Node* n2 = new Node(new_data);
        while (n1->next != nullptr) {
            n1 = n1->next;
        }
        n1->next = n2;
        n2->next = nullptr;
    }
 
    bool isPresent(Node* head, int data)
    {
        Node* t = head;
        while (t != nullptr) {
            if (t->data == data)
                return true;
            t = t->next;
        }
        return false;
    }
 
    LinkedList getIntersection(Node* head1, Node* head2)
    {
        unordered_set<int> hset;
        Node* n1 = head1;
        Node* n2 = head2;
        LinkedList result;
 
        while (n1 != nullptr) {
            if (hset.find(n1->data) == hset.end()) {
                hset.insert(n1->data);
            }
            n1 = n1->next;
        }
 
        while (n2 != nullptr) {
            if (hset.find(n2->data) != hset.end()) {
                result.push(n2->data);
            }
            n2 = n2->next;
        }
        return result;
    }
 
    LinkedList getUnion(Node* head1, Node* head2)
    {
        map<int, int> hmap;
        Node* n1 = head1;
        Node* n2 = head2;
        LinkedList result;
 
        while (n1 != nullptr) {
            if (hmap.find(n1->data) != hmap.end()) {
                hmap[n1->data]++;
            }
            else {
                hmap[n1->data] = 1;
            }
            n1 = n1->next;
        }
 
        while (n2 != nullptr) {
            if (hmap.find(n2->data) != hmap.end()) {
                hmap[n2->data]++;
            }
            else {
                hmap[n2->data] = 1;
            }
            n2 = n2->next;
        }
 
        for (auto it = hmap.begin(); it != hmap.end();
             it++) {
            result.append(it->first);
        }
        return result;
    }
};
 
int main()
{
    LinkedList llist1, llist2, intersection, union_list;
 
    llist1.push(20);
    llist1.push(4);
    llist1.push(15);
    llist1.push(10);
 
    llist2.push(10);
    llist2.push(2);
    llist2.push(4);
    llist2.push(8);
 
    intersection = intersection.getIntersection(
        llist1.head, llist2.head);
    union_list
        = union_list.getUnion(llist1.head, llist2.head);
 
    cout << "First List is" << endl;
    llist1.printList();
 
    cout << "Second List is" << endl;
    llist2.printList();
 
    cout << "Intersection List is" << endl;
    intersection.printList();
 
    cout << "Union List is" << endl;
    ;
    union_list.printList();
}
 
// This code is contributed by Gaurav_Arora


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 8 10 15 20 


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!
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads