Two Linked Lists are identical when they have same data and arrangement of data is also 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)
Read full article from Identical Linked Lists | GeeksforGeeks
Method 1 (Iterative)
bool
areIdentical(
struct
node *a,
struct
node *b)
{
while
(1)
{
/* base case */
if
(a == NULL && b == NULL)
{
return
1; }
if
(a == NULL && b != NULL)
{
return
0; }
if
(a != NULL && b == NULL)
{
return
0; }
if
(a->data != b->data)
{
return
0; }
/* If we reach here, then a and b are not NULL and their
data is same, so move to next nodes in both lists */
a = a->next;
b = b->next;
}
}
Method 2 (Recursive)
Recursive solution code is much cleaner than the 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
bool
areIdentical(
struct
node *a,
struct
node *b)
{
if
(a == NULL && b == NULL)
{
return
1; }
if
(a == NULL && b != NULL)
{
return
0; }
if
(a != NULL && b == NULL)
{
return
0; }
if
(a->data != b->data)
{
return
0; }
/* If we reach here, then a and b are not NULL and their
data is same, so move to next nodes in both lists */
return
areIdentical(a->next, b->next);
}