In: Computer Science
How would you show two linked lists are equal? (Java for Data Structures and Algorithms)
Below is the complete Java solution. If you face any difficulty while understanding it, Please let me know in the comments.
Approach:
Two linked lists are equal if they have the same data and arrangements. So, We need to traverse both the linked lists parallely and check if the corresponding node data are equal or not. If their exists even a single node whose values doesn't match, then linked lists are not equal.
Refer below codes to get the complete concept.
Code:
import java.util.*;
public class Main {
// Node to represent linked list
static class ListNode {
int data;
ListNode next;
ListNode (int data) {
this.data = data;
this.next = null;
}
}
// Function to check if two linked lists are equal or not
static boolean areLinkedListsEqual(ListNode head1, ListNode head2)
{
// Run loop till both the head nodes doesn't becomes null
while (head1 != null && head2 != null ) {
// if node vales are not equal, means linked lists are not equal,
so return false
if(head1.data != head2.data)
return false;
// move head pointers to next node
head1 = head1.next;
head2 = head2.next;
}
// if both the heads are not null, it means linked lists are not
equal
return (head1 == null && head2 == null);
}
public static void main(String[] args) {
// create two linked lists
ListNode head1 = new
ListNode(5);
head1.next = new ListNode(2);
ListNode head2 = new
ListNode(5);
head2.next = new ListNode(2);
// check if the linked lists are
equal or not
System.out.println(areLinkedListsEqual(head1,head2));
}
}
Screenshot:
Output: