Identical Linked Lists

Given the two singly Linked Lists respectively. The task is to check whether two linked lists are identical or not. 
Two Linked Lists are identical when they have the same data and with the same arrangement too. If both Linked Lists are identical then return true otherwise return false

Examples:

Input:
LinkedList1: 1->2->3->4->5->6 LinkedList2: 99->59->42->20 Output: false
Explanation:

As shown in figure linkedlists are not identical.
Input:
LinkedList1: 1->2->3->4->5
LinkedList2: 1->2->3->4->5
Output: true
Explanation:

As shown in figure both are identical.

Expected Time Complexity: O(n)
Expected Auxilliary Space: O(1)

Constraints:
1 <= length of lists <= 103


Approach 01:

bool areIdentical(struct Node *head1, struct Node *head2) {

    Node* temp1 = head1;
    Node* temp2 = head2;

    while (temp1 != nullptr && temp2 != nullptr) {
        if (temp1->data != temp2->data) {
            return false;
        }
        temp1 = temp1->next;
        temp2 = temp2->next;
    }

    return temp1 == nullptr && temp2 == nullptr;
}
def areIdentical(head1, head2):
    temp1 = head1
    temp2 = head2
    
    while temp1 is not None and temp2 is not None:
        if temp1.data != temp2.data:
            return False
        temp1 = temp1.next
        temp2 = temp2.next
    
    return temp1 is None and temp2 is None

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top