C++ Program For Finding Intersection Of Two Sorted Linked Lists
Last Updated :
24 Feb, 2023
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
Example:
Input:
First linked list: 1->2->3->4->6
Second linked list be 2->4->6->8,
Output: 2->4->6.
The elements 2, 4, 6 are common in
both the list so they appear in the
intersection list.
Input:
First linked list: 1->2->3->4->5
Second linked list be 2->3->4,
Output: 2->3->4
The elements 2, 3, 4 are common in
both the list so they appear in the
intersection list.
Method 1: Using Dummy Node.
Approach:
The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either 'a' or 'b' and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
// Link list node
struct Node
{
int data;
Node* next;
};
void push(Node** head_ref,
int new_data);
/* This solution uses the temporary
dummy to build up the result list */
Node* sortedIntersect(Node* a, Node* b)
{
Node dummy;
Node* tail = &dummy;
dummy.next = NULL;
/* Once one or the other
list runs out -- we're done */
while (a != NULL && b != NULL)
{
if (a->data == b->data)
{
push((&tail->next), a->data);
tail = tail->next;
a = a->next;
b = b->next;
}
// Advance the smaller list
else if (a->data < b->data)
a = a->next;
else
b = b->next;
}
return (dummy.next);
}
// UTILITY FUNCTIONS
/* Function to insert a node at
the beginning of the linked list */
void push(Node** head_ref, int new_data)
{
// Allocate node
Node* new_node =
(Node*)malloc(sizeof(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;
}
/* Function to print nodes in
a given linked list */
void printList(Node* node)
{
while (node != NULL)
{
cout << node->data <<" ";
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty lists
Node* a = NULL;
Node* b = NULL;
Node* intersect = NULL;
/* Let us create the first sorted
linked list to test the functions
Created linked list will be
1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted
linked list. Created linked list
will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
// Find the intersection two linked lists
intersect = sortedIntersect(a, b);
cout <<
"Linked list containing common items of a & b ";
printList(intersect);
}
Output:
Linked list containing common items of a & b
2 4 6
Complexity Analysis:
- Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively.
Only one traversal of the lists are needed. - Auxiliary Space: O(min(m, n)).
The output list can store at most min(m,n) nodes .
Method 2: Recursive Solution.
Approach:
The recursive approach is very similar to the above two approaches. Build a recursive function that takes two nodes and returns a linked list node. Compare the first element of both the lists.
- If they are similar then call the recursive function with the next node of both the lists. Create a node with the data of the current node and put the returned node from the recursive function to the next pointer of the node created. Return the node created.
- If the values are not equal then remove the smaller node of both the lists and call the recursive function.
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node
{
int data;
struct Node* next;
};
struct Node* sortedIntersect(struct Node* a,
struct Node* b)
{
// Base case
if (a == NULL || b == NULL)
return NULL;
// If both lists are non-empty
/* Advance the smaller list and
call recursively */
if (a->data < b->data)
return sortedIntersect(a->next, b);
if (a->data > b->data)
return sortedIntersect(a, b->next);
// Below lines are executed only
// when a->data == b->data
struct Node* temp =
(struct Node*)malloc(sizeof(struct Node));
temp->data = a->data;
// Advance both lists and call recursively
temp->next = sortedIntersect(a->next,
b->next);
return temp;
}
// UTILITY FUNCTIONS
/* Function to insert a node at
the beginning of the 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;
}
/* Function to print nodes in
a given linked list */
void printList(struct Node* node)
{
while (node != NULL)
{
cout << " " << node->data;
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty lists
struct Node* a = NULL;
struct Node* b = NULL;
struct Node* intersect = NULL;
/* Let us create the first sorted
linked list to test the functions
Created linked list will be
1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted
linked list. Created linked list
will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
// Find the intersection two linked lists
intersect = sortedIntersect(a, b);
cout << "Linked list containing " <<
"common items of a & b ";
printList(intersect);
return 0;
}
// This code is contributed by shivanisinghss2110
Output:
Linked list containing common items of a & b
2 4 6
Complexity Analysis:
- Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively.
Only one traversal of the lists are needed. - Auxiliary Space: O(max(m, n)).
The output list can store at most m+n nodes.
Please refer complete article on Intersection of two Sorted Linked Lists for more details!
Similar Reads
C++ Program For Finding Intersection Point Of Two Linked Lists
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists hav
9 min read
C++ Program For Union And Intersection Of Two Linked Lists
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->20List2: 8->4->2->10Output:Int
9 min read
C++ Program For Finding The Length Of Loop In Linked List
Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Re
3 min read
C++ Program For Finding Length Of A Linked List
Write a function to count the number of nodes in a given singly linked list. For example, the function should return 5 for linked list 1->3->1->2->1. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Iterative Solution: 1) Initialize count as 0 2) Initia
4 min read
Get the Intersection point of two Linked List by counting nodes
There are two singly linked lists in a system. By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted Y shaped list. Write a program to get the point where two linked list merge. Above diagram shows an example with two linked list having
8 min read
C++ Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read
How to Find Intersection of Two Multisets in C++?
In C++, multisets are a type of associative container similar to the set, with the exception that multiple elements can have the same values. Intersection means the elements that are common between two datasets. In this article, we will see how to find the intersection of two Multisets in C++. Examp
3 min read
C++ Program For Inserting Node In The Middle Of The Linked List
Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
5 min read
C++ Program For Detecting Loop In A Linked List
Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. The following are different ways of doing this. Solution 1: Hashing Approach: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reach
11 min read
C++ Program For Merge Sort For Doubly Linked List
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read