C++ Program To Check If Two Linked Lists Are Identical
Last Updated :
10 Feb, 2023
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical.
Method 1 (Iterative):
To identify if two lists are identical, we need to traverse both lists simultaneously, and while traversing we need to compare data.
C++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
bool areIdentical( struct Node *a,
struct Node *b)
{
while (a != NULL && b != NULL)
{
if (a->data != b->data)
return false ;
a = a->next;
b = b->next;
}
return (a == NULL && b == NULL);
}
void push( struct Node** head_ref,
int new_data)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
struct Node *a = NULL;
struct Node *b = NULL;
push(&a, 1);
push(&a, 2);
push(&a, 3);
push(&b, 1);
push(&b, 2);
push(&b, 3);
if (areIdentical(a, b))
cout << "Identical" ;
else
cout << "Not identical" ;
return 0;
}
|
Output:
Identical
Time Complexity: O(n) where n is the length of the smaller list among a and b.
Method 2 (Recursive):
Recursive solution code is much cleaner than iterative code. You probably wouldn’t want to use the recursive version for production code, however, because it will use stack space which is proportional to the length of the lists.
C++
bool areIdentical(Node *a, Node *b)
{
if (a == NULL && b == NULL)
return true ;
if (a != NULL && b != NULL)
return (a->data == b->data) &&
areIdentical(a->next, b->next);
return false ;
}
|
Time Complexity: O(n) for both iterative and recursive versions. n is the length of the smaller list among a and b.
Auxiliary Space: O(n) for call stack because using recursion
Please refer complete article on Identical Linked Lists for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...