top of page
Search

Palindrome check using stack and queue

  • Ben
  • Jan 19, 2018
  • 1 min read

#include <iostream> #include <stack> #include <queue> using namespace std;

class Solution { stack<char> s; queue<char> q; // Pushes character into stack public: void pushCharacter(char i) { s.push(i); } // Enqueue character into queue void enqueueCharacter(char i) { q.push(i); } // remove character from stack char popCharacter() { char temp= s.top(); s.pop(); return temp; } //remove character from queue char dequeueCharacter() { char temp = q.front(); q.pop(); return temp; }

}; int main() { // read the string s. string s; getline(cin, s); // create the Solution class object p. Solution obj; // push/enqueue all the characters of string s to stack. for (int i = 0; i < s.length(); i++) { obj.pushCharacter(s[i]); obj.enqueueCharacter(s[i]); } bool isPalindrome = true; // pop the top character from stack. // dequeue the first character from queue. // compare both the characters. for (int i = 0; i < s.length() / 2; i++) { if (obj.popCharacter() != obj.dequeueCharacter()) { isPalindrome = false; break; } } // finally print whether string s is palindrome or not. if (isPalindrome) { cout << "The word, " << s << ", is a palindrome."; } else { cout << "The word, " << s << ", is not a palindrome."; } return 0; }

 
 
 

Recent Posts

See All
Swap two words in a byte

#include <iostream> using namespace std; int main() { unsigned int data=0x1234; cout<<"data before swapping :"<<hex<<data<<endl; ...

 
 
 
Fibonacci series

#include <iostream> using namespace std; int main() { // Getting the input of fibonacci series long int n; cout<<"Enter the size of...

 
 
 

Comments


bottom of page