Description
假设称正读和反读都相同的字符序列为“回文”,例如,‘abba‘ 和 ‘abcba‘是回文,‘abcde‘ 和 ‘ababab‘ 则不是回文。试写一个算法判别读入的一个以‘@‘为结束符的字符序列是否是“回文”。
Input
abcba
Output
是回文
Sample Input
ababab
Sample Output
不是回文
#include<iostream> #include<cstdlib> #define MaxSize 50 using namespace std; char e; typedef struct { char data[MaxSize]; int top; }SqStack; void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } bool Push(SqStack *&s,char e)//进栈 { if(s->top==MaxSize-1) return false ; s->top++; s->data[s->top]=e; return true; } bool Pop(SqStack*&s, char &e)//出栈 { if(s->top==-1) return false; e=s->data[s->top]; s->top--; return true; } void DestroyStack(SqStack *&s) { free(s); } bool Judge(char str[]) { char e;int i,k; SqStack *st; InitStack(st); for(i=0;str[i]!='\0';i++)//进栈 { Push(st,str[i]);k=i; } str[k]='\0'; for(i=0;str[i]!='\0';i++)//栈里的元素和输入的比较,利用栈先进后出的特点判断 { Pop(st,e); //cout<<e<<' '; if(str[i]!=e) { DestroyStack(st); return false; } } DestroyStack(st); return true; } int main() { char a[MaxSize]; cin.getline(a,50,'@');//用getline从键盘上提取数据 if(Judge(a)) cout<<"是回文"<<endl; else cout<<"不是回文"<<endl; return 0; }