Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavascript Program To Check If Two Linked Lists Are Identical

Javascript Program To Check If Two Linked Lists Are Identical

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 (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.

Javascript




<script>
// A recursive javascript method to check if
// two linked lists are identical or not
function areIdenticalRecur(a,  b)
{
    // If both lists are empty
    if (a == null && b == null)
        return true;
 
    // If both lists are not empty, then
    // data of current nodes must match,
    // and same should be recursively true
    // for rest of the nodes.
    if (a != null && b != null)
        return (a.data == b.data) &&
               areIdenticalRecur(a.next, b.next);
 
    // If we reach here, then one of the lists
    // is empty and other is not
    return false;
}
 
/* Returns true if linked lists a and b
   are identical, otherwise false */
function areIdentical( listb)
{
    return areIdenticalRecur(this.head,
                             listb.head);
}
// This code contributed by aashish1995
</script>


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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments