7-1 回文判断 (300 分)
回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。编写一个程序,使用栈判定给定的字符序列是否为回文。
输入格式:
输入待判断的字符序列,按回车键结束,字符序列长度<20。
输出格式:
若字符序列是回文,输出“YES”;否则,输出“NO”。
输入样例:
abdba
输出样例:
YES
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define initSize 100
#define maxSize 20
typedef char Elemtype;
typedef struct {
Elemtype elem[20];
int top;//top 指向当前元素
int stackSize;
}SeqStack;
//创建于一个空栈
SeqStack* initStack ( ) {
SeqStack S=NULL;
S=(Elemtype)malloc(initSize*sizeof(Elemtype));
S->top = -1;
S->stackSize = initSize;
return S;
}
//入栈,每次一个元素
void Push ( SeqStack *S, Elemtype x ) {
S->top++;
S->elem[S->top] = x;
}
//退栈,每次一个,返回相应的元素
Elemtype Pop ( SeqStack *S ) {
Elemtype x;
x = S->elem[S->top];
S->top--;
return x;
}
int main(){
SeqStack* S;
S=initStack();
char a[maxSize];
gets(a);
int len=0;
len=strlen(a);
if(len==1){
printf("YES");
return 0;
}
for(int i=0;i<len;i++){
Push(S,a[i]);
}
Elemtype index;
int flag=0;
for(int i=0;i<len/2;i++){
index=Pop(S);
if(a[i]==index)
flag=1;
else
flag=0;
}
if(flag)
printf("YES");
else
printf("NO");
return 0;
}