A string that reads the same thing as the inverse reads (excluding whitespace) is called palindrome.
Such as string: "Madam im Adam", "Dad" are palindrome.
Design algorithm to determine whether a string is palindrome,
requires the use of stack to achieve discrimination of palindrome.
#include <iostream>
#include <cstring>
using namespace std;
#define MaxSize 1000
class SqStack
{
public:
SqStack();
bool isEmpty();
void push(char ch);
char pop();
void Print();
void Palindrome();
private:
char data[MaxSize];
int top;
};
SqStack::SqStack()
{
this->top=-1;
}
bool SqStack::isEmpty()
{
if(this->top=-1)
return true;
else
return false;
}
void SqStack::push(char ch)
{
if(top == MaxSize-1)
cout<<"栈满"<<endl;
else
{
++top;
data[top] = ch;
}
}
char SqStack::pop()
{
char ch;
if(top==-1)
{
cout<<"栈空"<<endl;
return 0;
}
else
{
ch = data[top];
--top;
}
return ch;
}
void SqStack::Palindrome()
{
bool tag = true;
int n = top;
for(int i =0;i<(top+1)/2;++i)
{
if(data[i]!=data[n])
{
tag = false;
break;
}
n--;
}
if(tag)
cout<<"回文数"<<endl;
else
cout<<"非回文数"<<endl;
}
void SqStack::Print()
{
if(top==-1)
cout<<"栈空"<<endl;
else
cout<<data<<endl;
}
int main()
{
SqStack sq1,sq2;
string s;
cin>>s;
char q;
cout<<"字符串长度:"<<s.length()<<endl;
for(int i= 0;i<s.length()/2;++i)
{
sq1.push(s[i]);
sq2.push(s[s.length()-1-i]);
}
cout<<"字符串为:"<<s<<endl;
int tag=true;
for(int i= 0;i<s.length()/2;++i)
{
if(sq1.pop()!=sq2.pop())
{
tag = false;
break;
}
}
if(tag)
cout<<s<<"是回文数"<<endl;
else
cout<<s<<"不是回文数"<<endl;
//sq.Palindrome();
//sq.pop(q);//出栈
return 0;
}