Subscribe to EdwinNameless' Fake Blog        RSS Feed

Palindrome with a Stack in C++

Icon Leave Comment
As I'm sick of seeing this question over and over again in the fora, here is a solution. The idea of the stack is that as it is FILO (I'll let you look that one up to explain "your" fantastic piece of work to your teacher when you submit my solution): the consequence is that when you pop the characters out of the stack, they come in the reverse order. If you therefore compare the string built with the characters as they come out of the stack with the original string, it is the reverse of it. And guess what? In a palindrome, the original and the reverse are the same.

So, with no further ado:

#include <iostream>
#include <string>
#include <stack>

using namespace std;

bool is_palindrome(string input) {
  stack<char> s;
  string rev;
  string::iterator iter;
  for(iter = input.begin(); iter != input.end(); ++iter) {
  while (!s.empty()) {
	rev +=;
  return (input == rev);

int main() {
  std::string str;
  std::cout << "Enter a string." << endl;
  std::cin >> str;
  std::cout << (is_palindrome(str) ? "palindrome" : "not palindrome") << std::endl;
  return 0;

I let you handle the mixed case cases, the punctuation, the occasional whitespace (even though I doubt you'll even bother given the amount of effort you have shown so far...).

For a solution in Ruby (still with stack):

def palindrome?(input)
  stack = []
  output = ""
  input.each_char{|x| stack.push x}
  while not stack.empty?
	output << stack.pop
  output == input

input = gets.chomp
puts (palindrome?(input) ? "palindrome": "not palindrome")

And for the laugh:

input = gets.chomp
puts (input.reverse == input ? "palindrome": "not palindrome")

0 Comments On This Entry


Search My Blog

Recent Entries

Recent Comments

My Picture

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)