Compare two Linked List of Strings - GeeksforGeeks

19 Apr, 2022
Given two linked lists L1 and L2 in which in every node a string is stored. The task is to check whether the strings combining all the nodes are similar or not. 
Examples:
Input: L1 = [“He”, “llo”, “wor”, “ld”],            L2 = [“H”, “e”, “ll”, “owo”, “r”, “ld”]Output: trueExplanation: both lists makes the string of “Helloworld”.
Input: L1 = [“w”, “o”, “l”, “d”],            L2 = [“wo”, “d”, “rl”]Output: falseExplanation: L1 makes “world” but L2 makes “wodrl” both are different.
Input: L1 = [“w”, “”, “orl”, “d”],            L2 = [“worl”, “”, “”, “”, “d”]Output: trueExplanation: both lists makes the string of “world”.
Naive Approach: This is the simple approach. Traverse both the lists and store their values in another string, then compare both strings if equal return true else return false.
Below is the implementation of the above approach.
C++
Java
Python3
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Structure of Node of linked listclass Node {public:    string s;    Node* next;    Node(string s)    {        this->s = s;        next = NULL;    }}; // Function to compare if two linkedlists// are similar or notbool compare(Node* list1, Node* list2){    // Declare string variables to store    // the strings formed from the linked lists    string s1, s2;     while (list1 != NULL) {        s1 += list1->s;        list1 = list1->next;    }    while (list2 != NULL) {        s2 += list2->s;        list2 = list2->next;    }    return s1 == s2;} // Driver Codeint main(){    Node* n1 = new Node("w");    Node* head1 = n1;    Node* n2 = new Node("");    Node* n3 = new Node("orl");    Node* n4 = new Node("d");    Node* n5 = new Node("worl");    Node* head2 = n5;    Node* n6 = new Node("");    Node* n7 = new Node("");    Node* n8 = new Node("nd");    n1->next = n2;    n2->next = n3;    n3->next = n4;    n5->next = n6;    n6->next = n7;    n7->next = n8;     if (compare(head1, head2) == true)        cout << "true";    else        cout << "false";    return 0;}
// Java program for above approachimport java.util.*; class GFG{ // Structure of Node of linked liststatic class Node {    String s;    Node next;    Node(String s)    {        this.s = s;        next = null;    }}; // Function to compare if two linkedlists// are similar or notstatic boolean compare(Node list1, Node list2){       // Declare String variables to store    // the Strings formed from the linked lists    String s1 ="", s2="";     while (list1 != null) {        s1 += list1.s;        list1 = list1.next;    }    while (list2 != null) {        s2 += list2.s;        list2 = list2.next;    }    return s1 == s2;} // Driver Codepublic static void main(String[] args){    Node n1 = new Node("w");    Node head1 = n1;    Node n2 = new Node("");    Node n3 = new Node("orl");    Node n4 = new Node("d");    Node n5 = new Node("worl");    Node head2 = n5;    Node n6 = new Node("");    Node n7 = new Node("");    Node n8 = new Node("nd");    n1.next = n2;    n2.next = n3;    n3.next = n4;    n5.next = n6;    n6.next = n7;    n7.next = n8;     if (compare(head1, head2) == true)        System.out.print("true");    else        System.out.print("false");}} // This code is contributed by umadevi9616
# Python code for the above approach # Structure of Node of linked listclass Node:    def __init__(self,str):        self.s = str        self.next = None # Function to compare if two linkedlists# are similar or notdef compare(list1, list2):     # Declare string variables to store    # the strings formed from the linked lists    s1,s2 = "",""     while (list1 != None):        s1 += list1.s        list1 = list1.next    while (list2 != None):        s2 += list2.s        list2 = list2.next     return s1 == s2 # Driver Coden1 = Node("w")head1 = n1n2 = Node("")n3 = Node("orl")n4 = Node("d")n5 = Node("worl")head2 = n5n6 = Node("")n7 = Node("")n8 = Node("nd")n1.next = n2n2.next = n3n3.next = n4n5.next = n6n6.next = n7n7.next = n8 if (compare(head1, head2) == True):    print("true")else:    print("false") # This code is contributed by shinjanpatra
<script>      // JavaScript code for the above approach       // Structure of Node of linked list      class Node {          constructor(str) {              this.s = str;              this.next = null;          }      };       // Function to compare if two linkedlists      // are similar or not      function compare(list1, list2)      {                 // Declare string variables to store          // the strings formed from the linked lists          let s1 = "", s2 = "";           while (list1 != null) {              s1 += list1.s;              list1 = list1.next;          }          while (list2 != null) {              s2 += list2.s;              list2 = list2.next;          }          return s1 == s2;      }       // Driver Code      let n1 = new Node("w");      let head1 = n1;      let n2 = new Node("");      let n3 = new Node("orl");      let n4 = new Node("d");      let n5 = new Node("worl");      let head2 = n5;      let n6 = new Node("");      let n7 = new Node("");      let n8 = new Node("nd");      n1.next = n2;      n2.next = n3;      n3.next = n4;      n5.next = n6;      n6.next = n7;      n7.next = n8;       if (compare(head1, head2) == true)          document.write("true");      else          document.write("false"); // This code is contributed by Potta Lokesh  </script>
  
false
Time Complexity: O(N+M) where N and M are lengths of the strings.Auxiliary Space:  O(N+M) 
Efficient Approach: This problem can be solved by using Two pointers approach. Follow the steps below to solve the given problem.
Traverse both the lists while maintaining two pointers for the characters.
Compare each of the characters separately. If different, return false otherwise, continue to compare.
If the pointer’s value becomes the size of a string in a node, then move to the next node.
Repeat the steps until the nodes do not become NULL.
Below is the implementation of the above approach.
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Structure of Node of a linked listclass Node {public:    string s;    Node* next;    Node(string s)    {        this->s = s;        next = NULL;    }}; // Compare functionbool compare(Node* list1, Node* list2){    int i = 0, j = 0;     while (list1 != NULL && list2 != NULL) {        while (i < list1->s.size() &&               j < list2->s.size()) {            if (list1->s[i] != list2->s[j])                return false;            i++;            j++;        }        if (i == list1->s.size()) {            i = 0;            list1 = list1->next;        }        if (j == list2->s.size()) {            j = 0;            list2 = list2->next;        }    }    return list1 == NULL && list2 == NULL;} // Driver Codeint main(){    Node* n1 = new Node("w");    Node* head1 = n1;    Node* n2 = new Node("");    Node* n3 = new Node("orl");    Node* n4 = new Node("d");    Node* n5 = new Node("worl");    Node* head2 = n5;    Node* n6 = new Node("");    Node* n7 = new Node("");    Node* n8 = new Node("nd");    n1->next = n2;    n2->next = n3;    n3->next = n4;    n5->next = n6;    n6->next = n7;    n7->next = n8;     if (compare(head1, head2) == true)        cout << "true";    else        cout << "false";    return 0;}
  
false
Time Complexity: O(N+M) where N and M are length of the strings. Auxiliary Space:  O(1). 
 
lokeshpotta20
umadevi9616
shinjanpatra
Algo-Geek 2021
Algo Geek
Linked List
Strings
Linked List
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Check if the given string is valid English word or not
Divide given number into two even parts
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Check if an edge is a part of any Minimum Spanning Tree
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)