Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Identical Linked Lists
Next article icon

Identical Linked Lists

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two singly linked lists. The task is to determine if the two linked lists are identical or not. Two linked lists are considered identical if they contain the same data in the same order. If the linked lists are identical, 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 Approach] By Traversal of Linked List - O(n) time and O(1) Space:

The idea is to traverse both the lists simultaneously and while traversing we need to compare data.

Code Implementation:

C++
// C++ program to check if two linked lists // are identical or not #include <bits/stdc++.h> using namespace std;  struct Node {     int data;     Node *next;      Node(int val)     {         data = val;         next = nullptr;     } };  // Returns true if linked lists head1 and head2 are // identical, otherwise false bool areIdentical(Node *head1, Node *head2) {     while (head1 != nullptr && head2 != nullptr)     {         if (head1->data != head2->data)             return false;          // Move to next nodes in both lists          head1 = head1->next;         head2 = head2->next;     }      // If linked lists are identical,     // both 'head1' and 'head2' must be NULL     return (head1 == nullptr && head2 == nullptr); }  int main() {     // Create first linked list: 3 -> 2 -> 1     Node *head1 = new Node(3);     head1->next = new Node(2);     head1->next->next = new Node(1);      // Create second linked list: 3 -> 2 -> 1     Node *head2 = new Node(3);     head2->next = new Node(2);     head2->next->next = new Node(1);      // Function call     if (areIdentical(head1, head2))         cout << "True";     else         cout << "False";      return 0; } 
C
// C program to check if two linked lists // are identical or not #include <stdio.h>  struct Node {     int data;     struct Node* next; };  // Returns true if linked lists head1 and head2 are  // identical, otherwise false int areIdentical(struct Node* head1, struct Node* head2) {     while (head1 != NULL && head2 != NULL) {         if (head1->data != head2->data)             return 0;          // Move to next nodes in both lists         head1 = head1->next;         head2 = head2->next;     }      // If linked lists are identical,    	// both 'head1' and 'head2' must be NULL     return (head1 == NULL && head2 == NULL); }  struct Node* createNode(int val) {     struct Node* new_node =        (struct Node*)malloc(sizeof(struct Node));     new_node->data = val;     new_node->next = NULL;     return new_node; }  int main() {     // Create first linked list: 3 -> 2 -> 1     struct Node* head1 = createNode(3);     head1->next = createNode(2);     head1->next->next = createNode(1);      // Create second linked list: 3 -> 2 -> 1     struct Node* head2 = createNode(3);     head2->next = createNode(2);     head2->next->next = createNode(1);      // Function call     if (areIdentical(head1, head2))         printf("True\n");     else         printf("False\n");      return 0; } 
Java
// Java program to check if two linked lists // are identical or not  class Node {     int data;     Node next;      Node(int val)     {         data = val;         next = null;     } }  class GfG {      // Returns true if linked lists head1 and head2 are     // identical, otherwise false     static boolean areIdentical(Node head1, Node head2)     {         while (head1 != null && head2 != null) {             if (head1.data != head2.data)                 return false;              /* Move to next nodes in both lists */             head1 = head1.next;             head2 = head2.next;         }          // If linked lists are identical,         // both 'head1' and 'head2' must be NULL         return (head1 == null && head2 == null);     }      public static void main(String[] args)     {         // Create first linked list: 3 -> 2 -> 1         Node head1 = new Node(3);         head1.next = new Node(2);         head1.next.next = new Node(1);          // Create second linked list: 3 -> 2 -> 1         Node head2 = new Node(3);         head2.next = new Node(2);         head2.next.next = new Node(1);          // Function call         if (areIdentical(head1, head2))             System.out.println("True");         else             System.out.println("False");     } } 
Python
# Python program to check if two linked lists # are identical or not  class Node:     def __init__(self, val):         self.data = val         self.next = None  # Returns true if linked lists head1 and head2 are # identical, otherwise false def areIdentical(head1, head2):     while head1 is not None and head2 is not None:         if head1.data != head2.data:             return False          # Move to next nodes in both lists         head1 = head1.next         head2 = head2.next      # If linked lists are identical,     # both 'head1' and 'head2' must be None     return head1 is None and head2 is None   if __name__ == "__main__":     # Create first linked list: 3 -> 2 -> 1     head1 = Node(3)     head1.next = Node(2)     head1.next.next = Node(1)      # Create second linked list: 3 -> 2 -> 1     head2 = Node(3)     head2.next = Node(2)     head2.next.next = Node(1)      # Function call     if areIdentical(head1, head2):         print("True")     else:         print("False") 
C#
// C# program to check if two linked lists // are identical or not using System;  public class Node {     public int Data;     public Node Next;      public Node(int val)     {         Data = val;         Next = null;     } }  class GfG {      // Returns true if linked lists head1 and head2 are     // identical, otherwise false     static bool AreIdentical(Node head1, Node head2)     {         while (head1 != null && head2 != null) {             if (head1.Data != head2.Data)                 return false;              // Move to next nodes in both lists             head1 = head1.Next;             head2 = head2.Next;         }          // If linked lists are identical,         // both 'head1' and 'head2' must be NULL         return (head1 == null && head2 == null);     }      public static void Main(string[] args)     {         // Create first linked list: 3 -> 2 -> 1         Node head1 = new Node(3);         head1.Next = new Node(2);         head1.Next.Next = new Node(1);          // Create second linked list: 3 -> 2 -> 1         Node head2 = new Node(3);         head2.Next = new Node(2);         head2.Next.Next = new Node(1);          if (AreIdentical(head1, head2))             Console.WriteLine("True");         else             Console.WriteLine("False");     } } 
JavaScript
// JavaScript program to check if two linked lists // are identical or not  class Node {     constructor(val) {         this.data = val;         this.next = null;     } }  // Returns true if linked lists head1 and head2 are  // identical, otherwise false function areIdentical(head1, head2) {     while (head1 !== null && head2 !== null) {         if (head1.data !== head2.data) {             return false;         }          // Move to next nodes in both lists         head1 = head1.next;         head2 = head2.next;     }      // If linked lists are identical,      // both 'head1' and 'head2' must be null     return head1 === null && head2 === null; }  // Create first linked list: 3 -> 2 -> 1 let head1 = new Node(3); head1.next = new Node(2); head1.next.next = new Node(1);  // Create second linked list: 3 -> 2 -> 1 let head2 = new Node(3); head2.next = new Node(2); head2.next.next = new Node(1);  if (areIdentical(head1, head2)) {     console.log("True"); } else {     console.log("False"); } 

Output
True

Time Complexity: O(n), Here n is the length of the smaller list among two linked list.
Auxiliary Space: O(1).


Next Article
Identical Linked Lists

K

kartik
Improve
Article Tags :
  • Linked List
  • DSA
Practice Tags :
  • Linked List

Similar Reads

    Comparing Python Lists Without Order
    Sometimes we need to compare two lists without worrying about the order of elements. This is particularly useful when checking if two lists contain the same elements regardless of their arrangement. In this article, we'll explore different ways to compare Python lists without considering order.Using
    3 min read
    Interesting facts about Python Lists
    Python lists are one of the most powerful and flexible data structures. Their ability to store mixed data types, support dynamic resizing and provide advanced features like list comprehension makes them an essential tool for Python developers. However, understanding their quirks, like memory usage a
    6 min read
    Initializing a List in Java
    The Java.util.List is a child interface of Collection. It is an ordered collection of objects where duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by the ArrayList, LinkedList, Vector, and
    6 min read
    Python | Checking if starting digits are similar in list
    Sometimes we may face a problem in which we need to find a list if it contains numbers with the same digits. This particular utility has an application in day-day programming. Let's discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach t
    8 min read
    Output of Python program | Set 6 (Lists)
    Prerequisite - Lists in Python Predict the output of the following Python programs. These question set will make you conversant with List Concepts in Python programming language. Program 1 Python list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print &quot;list1[0]:
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences