Open In App

C Program For Union And Intersection Of Two Linked Lists

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 <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
// Link list node
struct Node
{
    int data;
    struct Node* next;
};
 
/* 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* result = NULL;
    struct Node *t1 = head1, *t2 = head2;
 
    // 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 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 off 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)
    {
        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)
{
    struct Node* t = head;
    while (t != NULL)
    {
        if (t->data == data)
            return 1;
        t = t->next;
    }
    return 0;
}
 
// Driver code
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 list
       8->4->2->10 */
    push(&head2, 10);
    push(&head2, 2);
    push(&head2, 4);
    push(&head2, 8);
 
    intersecn = getIntersection(head1,
                                head2);
    unin = getUnion(head1, head2);
 
    printf("First list is ");
    printList(head1);
 
    printf("Second list is ");
    printList(head2);
 
    printf("Intersection list is ");
    printList(intersecn);
 
    printf("Union list is ");
    printList(unin);
 
    return 0;
}


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.

  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.

Below is the implementation of above approach:

C




#include <stdio.h>
#include <stdlib.h>
 
struct Node {
    int data;
    struct Node* next;
};
 
struct Node* createNode(int data)
{
    struct Node* newNode
        = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}
 
void printLinkedList(struct Node* head)
{
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d-->", temp->data);
        temp = temp->next;
    }
    printf("None\n");
}
 
struct Node* getUnion(struct Node* ll1, struct Node* ll2)
{
    struct Node* tail = NULL;
    struct Node* head = NULL;
 
    while (ll1 != NULL || ll2 != NULL) {
        if (ll1 == NULL) {
            if (tail == NULL) {
                tail = createNode(ll2->data);
                head = tail;
            }
            else {
                tail->next = createNode(ll2->data);
                tail = tail->next;
            }
            ll2 = ll2->next;
        }
        else if (ll2 == NULL) {
            if (tail == NULL) {
                tail = createNode(ll1->data);
                head = tail;
            }
            else {
                tail->next = createNode(ll1->data);
                tail = tail->next;
            }
            ll1 = ll1->next;
        }
        else {
            if (ll1->data < ll2->data) {
                if (tail == NULL) {
                    tail = createNode(ll1->data);
                    head = tail;
                }
                else {
                    tail->next = createNode(ll1->data);
                    tail = tail->next;
                }
                ll1 = ll1->next;
            }
            else if (ll1->data > ll2->data) {
                if (tail == NULL) {
                    tail = createNode(ll2->data);
                    head = tail;
                }
                else {
                    tail->next = createNode(ll2->data);
                    tail = tail->next;
                }
                ll2 = ll2->next;
            }
            else {
                if (tail == NULL) {
                    tail = createNode(ll1->data);
                    head = tail;
                }
                else {
                    tail->next = createNode(ll1->data);
                    tail = tail->next;
                }
                ll1 = ll1->next;
                ll2 = ll2->next;
            }
        }
    }
    return head;
}
 
int main()
{
    // Create the first linked list
    struct Node* head1 = createNode(10);
    head1->next = createNode(20);
    head1->next->next = createNode(30);
    head1->next->next->next = createNode(40);
    head1->next->next->next->next = createNode(50);
    head1->next->next->next->next->next = createNode(60);
    head1->next->next->next->next->next->next
        = createNode(70);
 
    // Create the second linked list
    struct Node* head2 = createNode(10);
    head2->next = createNode(30);
    head2->next->next = createNode(50);
    head2->next->next->next = createNode(80);
    head2->next->next->next->next = createNode(90);
 
    struct Node* head = getUnion(head1, head2);
    printLinkedList(head);
 
    // Free allocated memory
    while (head != NULL) {
        struct Node* temp = head;
        head = head->next;
        free(temp);
    }
 
    return 0;
}


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 <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
struct Node {
    int data;
    struct Node* next;
};
 
typedef struct Node Node;
 
struct LinkedList {
    Node* head;
};
 
typedef struct LinkedList LinkedList;
 
void printList(Node* head)
{
    Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}
 
void push(Node** head, int new_data)
{
    Node* new_node = (Node*)malloc(sizeof(Node));
    if (new_node == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    new_node->data = new_data;
    new_node->next = *head;
    *head = new_node;
}
 
void append(Node** head, int new_data)
{
    if (*head == NULL) {
        Node* new_node = (Node*)malloc(sizeof(Node));
        if (new_node == NULL) {
            printf("Memory allocation failed.\n");
            exit(1);
        }
        new_node->data = new_data;
        new_node->next = NULL;
        *head = new_node;
        return;
    }
    Node* n1 = *head;
    Node* n2 = (Node*)malloc(sizeof(Node));
    if (n2 == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    n2->data = new_data;
    n2->next = NULL;
    while (n1->next != NULL) {
        n1 = n1->next;
    }
    n1->next = n2;
}
 
bool isPresent(Node* head, int data)
{
    Node* t = head;
    while (t != NULL) {
        if (t->data == data)
            return true;
        t = t->next;
    }
    return false;
}
 
LinkedList getIntersection(Node* head1, Node* head2)
{
    int hset[10000] = { 0 };
    Node* n1 = head1;
    Node* n2 = head2;
    LinkedList result;
    result.head = NULL;
 
    while (n1 != NULL) {
        if (hset[n1->data] == 0) {
            hset[n1->data] = 1;
        }
        n1 = n1->next;
    }
 
    while (n2 != NULL) {
        if (hset[n2->data] != 0) {
            push(&(result.head), n2->data);
        }
        n2 = n2->next;
    }
    return result;
}
 
LinkedList getUnion(Node* head1, Node* head2)
{
    int hmap[10000] = { 0 };
    Node* n1 = head1;
    Node* n2 = head2;
    LinkedList result;
    result.head = NULL;
 
    while (n1 != NULL) {
        if (hmap[n1->data] != 0) {
            hmap[n1->data]++;
        }
        else {
            hmap[n1->data] = 1;
        }
        n1 = n1->next;
    }
 
    while (n2 != NULL) {
        if (hmap[n2->data] != 0) {
            hmap[n2->data]++;
        }
        else {
            hmap[n2->data] = 1;
        }
        n2 = n2->next;
    }
 
    for (int i = 0; i < 10000; i++) {
        if (hmap[i] > 0) {
            append(&(result.head), i);
        }
    }
    return result;
}
 
int main()
{
    LinkedList llist1, llist2, intersection, union_list;
    llist1.head = NULL;
    llist2.head = NULL;
    intersection.head = NULL;
    union_list.head = NULL;
 
    push(&(llist1.head), 20);
    push(&(llist1.head), 4);
    push(&(llist1.head), 15);
    push(&(llist1.head), 10);
 
    push(&(llist2.head), 10);
    push(&(llist2.head), 2);
    push(&(llist2.head), 4);
    push(&(llist2.head), 8);
 
    intersection
        = getIntersection(llist1.head, llist2.head);
    union_list = getUnion(llist1.head, llist2.head);
 
    printf("First List is\n");
    printList(llist1.head);
 
    printf("Second List is\n");
    printList(llist2.head);
 
    printf("Intersection List is\n");
    printList(intersection.head);
 
    printf("Union List is\n");
    printList(union_list.head);
 
    // Free allocated memory
    Node* temp;
    while (llist1.head != NULL) {
        temp = llist1.head;
        llist1.head = llist1.head->next;
        free(temp);
    }
 
    while (llist2.head != NULL) {
        temp = llist2.head;
        llist2.head = llist2.head->next;
        free(temp);
    }
 
    while (intersection.head != NULL) {
        temp = intersection.head;
        intersection.head = intersection.head->next;
        free(temp);
    }
 
    while (union_list.head != NULL) {
        temp = union_list.head;
        union_list.head = union_list.head->next;
        free(temp);
    }
 
    return 0;
}


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!



Last Updated : 12 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads