Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

C++ Program For Comparing Two Strings Represented As Linked Lists

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater.

Input: list1 = g->e->e->k->s->a
       list2 = g->e->e->k->s->b
Output: -1

Input: list1 = g->e->e->k->s->a
       list2 = g->e->e->k->s
Output: 1

Input: list1 = g->e->e->k->s
       list2 = g->e->e->k->s
Output: 0


// C++ program to compare two strings
// represented as linked lists
using namespace std;
// Linked list Node
// structure
struct Node
    char c;
    struct Node *next;
// Function to create newNode
// in a linkedlist
Node* newNode(char c)
    Node *temp = new Node;
    temp->c = c;
    temp->next = NULL;
    return temp;
int compare(Node *list1,
            Node *list2)
    // Traverse both lists. Stop when
    // either end of a linked list is
    // reached or current characters
    // don't match
    while (list1 && list2 &&
           list1->c == list2->c)
        list1 = list1->next;
        list2 = list2->next;
    //  If both lists are not empty,
    // compare mismatching characters
    if (list1 && list2)
        return ((list1->c >
                 list2->c)? 1: -1);
    // If either of the two lists has
    // reached end
    if (list1 && !list2) return 1;
    if (list2 && !list1) return -1;
    // If none of the above conditions
    // is true, both lists have reached
    // end
    return 0;
// Driver code
int main()
    Node *list1 = newNode('g');
    list1->next = newNode('e');
    list1->next->next = newNode('e');
    list1->next->next->next =
    list1->next->next->next->next =
    list1->next->next->next->next->next =
    Node *list2 = newNode('g');
    list2->next = newNode('e');
    list2->next->next = newNode('e');
    list2->next->next->next =
    list2->next->next->next->next = 
    list2->next->next->next->next->next =
    cout << compare(list1, list2);
    return 0;



Time Complexity: O(M + N), where M and N represents the length of the given two linked lists.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Please refer complete article on Compare two strings represented as linked lists for more details!

My Personal Notes arrow_drop_up
Last Updated : 15 Jun, 2022
Like Article
Save Article
Similar Reads
Related Tutorials