
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a Doubly Linked List of Characters is Palindrome in C++
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
#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
Advertisements