C++: Checking if a String is Palindrome Using Stack

 

 

 

 

node.cpp

#include <string>
#include <iostream>
using namespace std;

class node
{
  friend class stack;
private:
  char data;
  node *next;
public:
  node(char,node *n=0);
};

node::node(char d,node *n)
{
  data = d;
  next = n;
}

 

stack.cpp:

#include "node.cpp"

class stack
{
private:
  node *top;
public:
  char pop();
  void push(char d);
  bool empty(){ return top==0;}
  bool full(){ return false;} // always return false
  bool check(string);
  stack(){top = 0;};
};

char stack::pop()
{
    char d;
    node *p = top;
    top = top->next;
    d = p->data;
    delete p;
    return d;
}

void stack::push(char d)
{
    top = new node(d,top);
}

bool stack::check(string str)
{
  char x;
  while(!empty()) // to clear the stack
    x = pop();

  for(int i=0;str[i]!= '\0';i++)
  {
    if(str[i] != ' ')
      if(!full())
        push(str[i]);
  }

  for(int k=0;str[k]!= '\0';k++)
  {
    if(str[k] != ' ')
      if(!empty())
      {
        x = pop();
        if(x != str[k])
          return false;
      }
      else
        return false;
  }
  return true;
}

 

main.cpp:

#include "stack.cpp"

int main()
{
  stack s;
  char n[50];

  cout << "enter a string to check Palindrome: ";
  cin.getline(n,50);
  if(s.check(n))
    cout << "YES" << endl;
  else
    cout << "NO" << endl;
  return 0;
}