Write a program in c++ that uses a stack to test whether a given string is a palindrome.
#include<iostream> #include<stack> using namespace std; bool isPalindrome(string candidate) { stack<char> s; for(int i = 0;i<candidate.length();i++){ if(islower(candidate[i]) || isdigit(candidate[i])){ s.push(candidate[i]); } } int k = 0; while(!s.empty()){ if(s.top() != candidate[k++]){ return false; } s.pop(); } return true; } int main() { string input; cout<<"Enter string: "; cin>>input; if(isPalindrome(input)){ cout<<input<<" is a palindrome"<<endl; } else{ cout<<input<<" is not a palindrome"<<endl; } return 0; }
Get Answers For Free
Most questions answered within 1 hours.