Java Program To Check If Two Linked Lists Are Identical
Last Updated :
03 Aug, 2022
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.
Java
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
boolean areIdentical(LinkedList listb)
{
Node a = this .head, b = listb.head;
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( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
llist1.push( 1 );
llist1.push( 2 );
llist1.push( 3 );
llist2.push( 1 );
llist2.push( 2 );
llist2.push( 3 );
if (llist1.areIdentical(llist2) == true )
System.out.println( "Identical " );
else
System.out.println( "Not identical " );
}
}
|
Output:
Identical
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.
Java
boolean areIdenticalRecur(Node a, Node b)
{
if (a == null && b == null )
return true ;
if (a != null && b != null )
return (a.data == b.data) &&
areIdenticalRecur(a.next, b.next);
return false ;
}
boolean areIdentical(LinkedList listb)
{
return areIdenticalRecur( this .head,
listb.head);
}
|
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...