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