Skip to content
Related Articles

Related Articles

Identical Linked Lists

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 19 Sep, 2022
View Discussion
Improve Article
Save Article

Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. Write a function to check if the given two linked lists are identical. 

Examples:

Input: a = 1->2->3->4, b = 1->2->3->4
Output: Identical

Input: a = 1->3->5->2, b = 1->3->4->6
Output: Not Identical

Recommended Practice

Check if Linked-Lists are identical using linear traversal:

To solve the problem follow the below idea:

To identify if two lists are identical, we need to traverse both lists simultaneously, and while traversing we need to compare data
 

Complete Interview Preparation - GFG Follow the given steps to solve the problem:

  • Traverse both the linked lists simultaneously
    • If the data of the current node for one linked list is not equal to the node of the other one, then return false
  • Return true, as both the linked lists are identical

Below is the implementation of the above approach:

C++




// An iterative C++ program to check if
// two linked lists are identical or not
#include <bits/stdc++.h>
using namespace std;
 
/* Structure for a linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* Returns true if linked lists a and b
are identical, otherwise false */
bool areIdentical(struct Node* a, struct Node* b)
{
    while (a != NULL && b != NULL) {
        if (a->data != b->data)
            return false;
 
        /* 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;
    }
 
    // If linked lists are identical, then
    // 'a' and 'b' must be NULL at this point.
    return (a == NULL && b == NULL);
}
 
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the
head of a list and an int, push a new node on the
front of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list off the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
// Driver Code
int main()
{
    /* The constructed linked lists are :
    a: 3->2->1
    b: 3->2->1 */
    struct Node* a = NULL;
    struct Node* b = NULL;
    push(&a, 1);
    push(&a, 2);
    push(&a, 3);
    push(&b, 1);
    push(&b, 2);
    push(&b, 3);
 
      // Function call
    if (areIdentical(a, b))
        cout << "Identical";
    else
        cout << "Not identical";
 
    return 0;
}
 
// This code is contributed
// by Akanksha Rai


C




// An iterative C program to check if two linked lists are
// identical or not
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
/* Structure for a linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* Returns true if linked lists a and b are identical,
   otherwise false */
bool areIdentical(struct Node* a, struct Node* b)
{
    while (a != NULL && b != NULL) {
        if (a->data != b->data)
            return false;
 
        /* 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;
    }
 
    // If linked lists are identical, then 'a' and 'b' must
    // be NULL at this point.
    return (a == NULL && b == NULL);
}
 
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
  of a list and an int, push a new node on the front
  of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
 
    /* put in the data  */
    new_node->data = new_data;
 
    /* link the old list off the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Driver code */
int main()
{
    /* The constructed linked lists are :
     a: 3->2->1
     b: 3->2->1 */
    struct Node* a = NULL;
    struct Node* b = NULL;
    push(&a, 1);
    push(&a, 2);
    push(&a, 3);
    push(&b, 1);
    push(&b, 2);
    push(&b, 3);
 
      // Function call
    areIdentical(a, b) ? printf("Identical")
                       : printf("Not identical");
 
    return 0;
}


Java




// An iterative Java program to check if two linked lists
// are identical or not
 
import java.io.*;
 
class LinkedList {
    Node head; // head of list
 
    /* Linked list Node*/
    class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Returns true if linked lists a and b are identical,
       otherwise false */
    boolean areIdentical(LinkedList listb)
    {
        Node a = this.head, b = listb.head;
        while (a != null && b != null) {
            if (a.data != b.data)
                return false;
 
            /* 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;
        }
 
        // If linked lists are identical, then 'a' and 'b'
        // must be null at this point.
        return (a == null && b == null);
    }
 
    /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
    /*  Given a reference (pointer to pointer) to the head
        of a list and an int, push a new node on the front
        of the list. */
 
    void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Driver code */
    public static void main(String args[])
    {
        LinkedList llist1 = new LinkedList();
        LinkedList llist2 = new LinkedList();
 
        /* The constructed linked lists are :
           llist1: 3->2->1
           llist2: 3->2->1 */
 
        llist1.push(1);
        llist1.push(2);
        llist1.push(3);
 
        llist2.push(1);
        llist2.push(2);
        llist2.push(3);
 
          // Function call
        if (llist1.areIdentical(llist2) == true)
            System.out.println("Identical ");
        else
            System.out.println("Not identical ");
    }
} /* This code is contributed by Rajat Mishra */


Python3




# An iterative Java program to check if
# two linked lists are identical or not
 
# Linked list Node
 
 
class Node:
    def __init__(self, d):
        self.data = d
        self.next = None
 
 
class LinkedList:
    def __init__(self):
        self.head = None  # head of list
 
    # Returns true if linked lists a and b
    # are identical, otherwise false
    def areIdentical(self, listb):
        a = self.head
        b = listb.head
        while (a != None and b != None):
            if (a.data != b.data):
                return False
 
            # 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
 
        # If linked lists are identical,
        # then 'a' and 'b' must be null
        # at this point.
        return (a == None and b == None)
 
    # UTILITY FUNCTIONS TO TEST fun1() and fun2()
    # Given a reference (pointer to pointer) to the
    # head of a list and an int, push a new node on
    # the front of the list.
 
    def push(self, new_data):
 
        # 1 & 2: Allocate the Node &
        # Put in the data
        new_node = Node(new_data)
 
        # 3. Make next of new Node as head
        new_node.next = self.head
 
        # 4. Move the head to point to new Node
        self.head = new_node
 
 
# Driver Code
if __name__ == "__main__":
  llist1 = LinkedList()
  llist2 = LinkedList()
 
  # The constructed linked lists are :
  # llist1: 3->2->1
  # llist2: 3->2->1
  llist1.push(1)
  llist1.push(2)
  llist1.push(3)
  llist2.push(1)
  llist2.push(2)
  llist2.push(3)
 
  # Function call
  if (llist1.areIdentical(llist2) == True):
      print("Identical ")
  else:
      print("Not identical ")
 
# This code is contributed by Prerna Saini


C#




// An iterative C# program to
// check if two linked lists
// are identical or not
using System;
 
public class LinkedList {
    Node head; // head of list
 
    /* Linked list Node*/
    public class Node {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Returns true if linked lists
    a and b are identical,
    otherwise false */
    bool areIdentical(LinkedList listb)
    {
        Node a = this.head, b = listb.head;
        while (a != null && b != null) {
            if (a.data != b.data)
                return false;
 
            /* 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;
        }
 
        // If linked lists are identical,
        // then 'a' and 'b' must
        // be null at this point.
        return (a == null && b == null);
    }
 
    /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
    /* Given a reference (pointer to pointer) to the head
        of a list and an int, push a new node on the front
        of the list. */
 
    void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Driver code */
    public static void Main(String[] args)
    {
        LinkedList llist1 = new LinkedList();
        LinkedList llist2 = new LinkedList();
 
        /* The constructed linked lists are :
        llist1: 3->2->1
        llist2: 3->2->1 */
 
        llist1.push(1);
        llist1.push(2);
        llist1.push(3);
 
        llist2.push(1);
        llist2.push(2);
        llist2.push(3);
 
          // Function call
        if (llist1.areIdentical(llist2) == true)
            Console.WriteLine("Identical ");
        else
            Console.WriteLine("Not identical ");
    }
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
// An iterative javascript program to check if two linked lists
// are identical or not
class LinkedList{
constructor() {
    this.head = null; // head of list
}
}
    /* Linked list Node */
    class Node {
 
constructor(d) {
            this.data = d;
            this.next = null;
        }
    }
 
    /*
     * Returns true if linked lists a and b are identical, otherwise false
     */
    function areIdentical( a,b) {
 
        while (a != null && b != null) {
            if (a.data != b.data)
                return false;
 
            /*
             * 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;
        }
 
        // If linked lists are identical, then 'a' and 'b' must
        // be null at this point.
        return (a == null && b == null);
    }
 
    /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
    /*
     * Given a reference (pointer to pointer) to the head of a list and an int, push
     * a new node on the front of the list.
     */
 
    function push(root,new_data) {
        /*
         * 1 & 2: Allocate the Node & Put in the data
         */
var new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = root;
 
        /* 4. Move the head to point to new Node */
        root = new_node;
        return root;
    }
 
    /* Driver program to test above functions */
     
        var llist1 = new LinkedList();
        var llist2 = new LinkedList();
 
        /*
         * The constructed linked lists are : llist1: 3->2->1 llist2: 3->2->1
         */
 
        llist1 = push(llist1,1);
        llist1 = push(llist1,2);
        llist1 = push(llist1,3);
 
        llist2 = push(llist2,1);
        llist2 = push(llist2,2);
        llist2 = push(llist2,3);
 
        if (areIdentical(llist1,llist2) == true)
            document.write("Identical ");
        else
            document.write("Not identical ");
 
 
// This code is contributed by Rajput-Ji
</script>


Output

Identical

Time Complexity: O(min(M, N)). Here, M and N are the sizes of the two linked lists and we have to traverse them till any one of them becomes null. So our time complexity will be a minimum of the size of two linked lists.
Auxiliary Space: O(1). As constant extra space is used.

Above approach using recursion:

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

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
/* Structure for a linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list off the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
// A recursive C++ function to check if two linked
// lists are identical or not
bool areIdentical(Node* a, Node* 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)
               && areIdentical(a->next, b->next);
 
    // If we reach here, then one of the lists
    // is empty and other is not
    return false;
}
 
// Driver Code
int main()
{
    /* The constructed linked lists are :
    a: 3->2->1
    b: 3->2->1 */
    struct Node* a = NULL;
    struct Node* b = NULL;
    push(&a, 1);
    push(&a, 2);
    push(&a, 3);
    push(&b, 1);
    push(&b, 2);
    push(&b, 3);
 
    // Function call
    if (areIdentical(a, b))
        cout << "Identical";
    else
        cout << "Not identical";
 
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




// C program to check if two linked lists are
// identical or not
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
/* Structure for a linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list off the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
// A recursive C function to check if two linked
// lists are identical or not
bool areIdentical(struct Node* a, struct Node* 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)
               && areIdentical(a->next, b->next);
 
    // If we reach here, then one of the lists
    // is empty and other is not
    return false;
}
 
/* Driver code */
int main()
{
    /* The constructed linked lists are :
     a: 3->2->1
     b: 3->2->1 */
    struct Node* a = NULL;
    struct Node* b = NULL;
    push(&a, 1);
    push(&a, 2);
    push(&a, 3);
    push(&b, 1);
    push(&b, 2);
    push(&b, 3);
 
    // Function call
    areIdentical(a, b) ? printf("Identical")
                       : printf("Not identical");
 
    return 0;
}


Java




// An iterative Java program to check if two linked lists
// are identical or not
 
import java.io.*;
 
class LinkedList {
    Node head; // head of list
 
    /* Linked list Node*/
    class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Returns true if linked lists a and b are identical,
       otherwise false */
    boolean areIdenticalRecur(Node a, Node 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 */
    boolean areIdentical(LinkedList listb)
    {
        return areIdenticalRecur(this.head, listb.head);
    }
 
    /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
    /*  Given a reference (pointer to pointer) to the head
        of a list and an int, push a new node on the front
        of the list. */
 
    void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Driver code */
    public static void main(String args[])
    {
        LinkedList llist1 = new LinkedList();
        LinkedList llist2 = new LinkedList();
 
        /* The constructed linked lists are :
           llist1: 3->2->1
           llist2: 3->2->1 */
 
        llist1.push(1);
        llist1.push(2);
        llist1.push(3);
 
        llist2.push(1);
        llist2.push(2);
        llist2.push(3);
 
        // Function call
        if (llist1.areIdentical(llist2) == true)
            System.out.println("Identical ");
        else
            System.out.println("Not identical ");
    }
} /* This code is contributed by Rajat Mishra */


C#




// An iterative C# program to
// check if two linked lists
// are identical or not
using System;
 
public class LinkedList {
    Node head; // head of list
 
    /* Linked list Node*/
    public class Node {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Returns true if linked lists
    a and b are identical,
    otherwise false */
    bool areIdenticalRecur(Node a, Node 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 */
    bool areIdentical(LinkedList listb)
    {
        return areIdenticalRecur(this.head, listb.head);
    }
 
    /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
    /* Given a reference (pointer to pointer) to the head
        of a list and an int, push a new node on the front
        of the list. */
 
    void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* Driver code */
    public static void Main(String[] args)
    {
        LinkedList llist1 = new LinkedList();
        LinkedList llist2 = new LinkedList();
 
        /* The constructed linked lists are :
        llist1: 3->2->1
        llist2: 3->2->1 */
 
        llist1.push(1);
        llist1.push(2);
        llist1.push(3);
 
        llist2.push(1);
        llist2.push(2);
        llist2.push(3);
 
        // Function call
        if (llist1.areIdentical(llist2) == true)
            Console.WriteLine("Identical ");
        else
            Console.WriteLine("Not identical ");
    }
}
 
// This code contributed by Rajput-Ji


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>


Output

Identical

Time Complexity: O(N). Here, N is the length of the smaller list among a and b
Auxiliary Space: O(N). The extra space is used in the recursion call stack.
 

Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!