C Program For Union And Intersection Of Two Linked Lists
Last Updated :
23 Jul, 2025
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.
- 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. 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;
}
Output10-->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;
}
OutputFirst 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!
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem