Palindrome using stack

Program Description

This program takes an input string from the user and checks whether the given string is plaindrome or not.
The program uses STL library's stack class.

Program
/*****************************************
*    code.cheraus.com
*
*    Palindrome using stack
*
*****************************************/

#include<iostream>
#include<stack>
#include<cstring>

using namespace std;


class str{
private:
        char word[100]; //character array to hold string
public:
        //function declarations
        void getdata();
        int pal();

};

/*
Function definition for getdata()

This function takes string input from the user.

*/

void str::getdata()
{
  cout<<"\nEnter the string : ";
  cin>>word;
}

/*
Function definition for pal()

This function tests a given string input and determines whether is it palindrome or not.
The function uses stack data structure to process the string.

Returns: 1 - if given string is palindrome
         0 - if given string is nota palindrome 

*/
int str::pal()
{
  stack<char> s;
  int i,j=0;
  for(i=0;i<strlen(word);i++)
   {
      s.push(word[i]);
   }
  
  while(!s.empty())
   {
     
     if(s.top()!=word[j])
       return 0;
      j++;
      s.pop();
   }
   return 1;
}



int main()
{
   str a;
   
   a.getdata();
   
   int ans = a.pal();
   
   if(ans==1)
    cout<<"\nThe given string is palindrome\n";
	
   else
    cout<<"\nThe given string is not a palindrome\n";
	
	
   return 0;
}

Output
Test Case 1:

Enter the string : cheraus
The given string is not a palindrome

Test Case 2:

Enter the string : nitin
The given string is palindrome

Test Case 3:

Enter the string : helloolleh
The given string is palindrome

Comments
comments powered by Disqus