回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。编写一个程序,使用栈判定给定的字符序列是否为回文。
输入格式:
输入待判断的字符序列,按回车键结束,字符序列长度<20。
输出格式:
若字符序列是回文,输出“YES”;否则,输出“NO”。
输入样例:
abdba
输出样例:
YES
利用c++内的stack来实现回文判断:
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
int main()
{
char sentence[20];
int length;
stack<char> s;
//gets(sentence);
cin>>sentence;
length=strlen(sentence);
for(int i=0;i<length/2;i++)
{
s.push(sentence[i]);
}
for(int i=length/2;i<length;i++)
{
if(s.top()==sentence[i])
{
s.pop();
}
}
if(s.empty()==1)
{
cout<<"YES";
}else cout<<"NO";
return 0;
}
以下是自定义顺序栈的代码演示:
#include <iostream>
#include <cstring>
#include <malloc.h>
#define STACK_INIT_SIZE 20
using namespace std;
typedef struct{
char *base;
char *top;
int satcksize;
}sqStack;
void initStack(sqStack &s)
{
if(!(s.base=(char*)malloc(STACK_INIT_SIZE*sizeof(char))))
exit(1);
s.top=s.base;
s.satcksize=STACK_INIT_SIZE;
}
void push(sqStack &s,char e)
{
*(s.top) ++= e;
}
void pop(sqStack &s,char &e)
{
if(s.base==s.top) return;
e = *--s.top;
}
int huiwen(char *p)
{
sqStack s;
int flag=1;
int i=1,j,len;
initStack(s);
len=strlen(p);
while(i<=len/2)
{
push(s,*p);
i++;
*p++; //*p++与p++
}
if(len%2==1) *p++;
for(j=i-1;j>=1;j--)
{
char a;
pop(s,a);
if(*p==a) *p++;
else flag=0;
}
return flag;
}
int main()
{
char p[21];
cin>>p;
if(huiwen(p)==1)
cout<<"YES";
else cout<<"NO";
return 0;
}