# C Program For Union And Intersection Of Two Linked Lists

• Last Updated : 20 Dec, 2021

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.
1. 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.
2. Union (list1, list2):
Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method.

## C

 `// C program to find union``// and intersection of two unsorted``// linked lists``#include ``#include ``#include `` ` `// 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 lits ``       ``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.

The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.
Please refer complete article on Union and Intersection of two Linked Lists for more details!

My Personal Notes arrow_drop_up