Check if a doubly linked list of characters is palindrome or not in C++

C++Server Side ProgrammingProgramming

Here we will see how to check a string is a palindrome or not using a Doubly linked list. Here we will push each character of a string inside one doubly linked list. There will be two pointers, left and right. Then start scanning from both sides. If a left character is the same as right character, then move the left pointer to the next node, and move the right pointer to the previous node. Otherwise, return false. This process will be continued until the left and right are pointing at the same node, or the right pointer is pointing to the previous element of the left pointer.

Example

 Live Demo

#include <iostream>
using namespace std;
class Node {
   public:
   char data;
   Node *next;
   Node *prev;
};
void getNode(Node** start, char new_data) {
   struct Node* newNode = new Node;
   newNode->data = new_data;
   newNode->next = (*start);
   newNode->prev = NULL;
   if ((*start) != NULL)
      (*start)->prev = newNode ;
      (*start) = newNode;
}
bool isPalindrome(Node *left) {
   if (left == NULL)
      return true;
   Node *right = left;
   while (right->next != NULL)
      right = right->next;
   while (left != right && right != left->prev) {
      if (left->data != right->data)
         return false;
      left = left->next;
      right = right->prev;
   }
return true;
}
int main() {
   Node* head = NULL;
   string str = "madam";
   for(int i = 0; i< str.length(); i++){
      getNode(&head, str[i]);
   }
   if (isPalindrome(head))
      cout << "This is Palindrome";
   else
      cout << "This is Not a Palindrome";
}

Output

This is Palindrome
raja
Published on 22-Oct-2019 07:53:44
Advertisements