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

Related Articles

C Program To Check If A Linked List Of Strings Forms A Palindrome

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

Given a linked list handling string data, check to see whether data is palindrome or not? Examples:

Input: a -> bc -> d -> dcb -> a -> NULL
Output: True
String "abcddcba" is palindrome.

Input: a -> bc -> d -> ba -> NULL
Output: False
String "abcdba" is not palindrome. 

The idea is very simple. Construct a string out of given linked list and check if the constructed string is palindrome or not. 


// Program to check if a given linked list
// of strings form a palindrome
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node
    string data;
    Node* next;
// A utility function to check if str
// is palindrome or not
bool isPalindromeUtil(string str)
    int length = str.length();
    // Match characters from beginning
    // and end.
    for (int i = 0; i < length / 2; i++)
        if (str[i] != str[length - i - 1])
            return false;
    return true;
// Returns true if string formed by linked
// list is palindrome
bool isPalindrome(Node *node)
    // Append all nodes to form a string
    string str = "";
    while (node != NULL)
        node = node->next;
    // Check if the formed string is
    // palindrome
    return isPalindromeUtil(str);
// A utility function to print a given
// linked list
void printList(Node *node)
    while (node != NULL)
        cout << node->data << " -> ";
        node = node->next;
/* Function to create a new node with
given data */
Node *newNode(const char *str)
    Node *new_node = new Node;
    new_node->data = str;
    new_node->next = NULL;
    return new_node;
// Driver code
int main()
    Node *head = newNode("a");
    head->next = newNode("bc");
    head->next->next = newNode("d");
    head->next->next->next =
    head->next->next->next->next =
    isPalindrome(head)? printf("true"):
    return 0;



Time Complexity: O(n), where n is the number of nodes in the given linked list.
Auxiliary Space: O(m), where m is the length of the string formed by the linked list.

Please refer complete article on Check if a linked list of strings forms a palindrome for more details!

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