回文是指正读反读均相同的字符序列,如“abba"和"abdba"均是回文,但”good"不是回文。试写一个算法判定给定的字符序列是否为回文。(附完整可运行代码)
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
typedef int Status;
typedef char SElemType;
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 2
struct SqStack
{
SElemType *top;
SElemType *base;
int stacksize;
};
void InitStack(SqStack &S)
{
S.base=(SElemType*)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
if(!S.base)
exit(-1);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
}
Status StackEmpty(SqStack S)
{
if(S.top==S.base)
return 1;
else
return 0;
}
void Push(SqStack &S,SElemType e)
{
if(S.top-S.base==S.stacksize)
{
S.base=(SElemType*)realloc(S.base,(S.stacksize+STACK_INCREMENT)*sizeof(SElemType));
if(!S.base)
exit(-1);
S.top=S.base+S.stacksize;
S.stacksize+=STACK_INCREMENT;
}
*S.top=e;
S.top++;
}
Status Pop(SqStack &S,SElemType &e)
{
if(S.top-S.base==0)
return 0;
e=*--S.top;
return 1;
}
int HuiWen(char *str)
{
SqStack S;
InitStack(S);
SElemType e;
int len = strlen(str);
int i,judge=1;
for(i = 0;i<len/2;i++)
{
Push(S,*str);
*str++;
}
if(len%2 == 1)
*str++;
for(int j=i;j>0;j--)
{
Pop(S,e);
if(*str == e)
*str++;
else
judge = 0;
}
return judge;
}
int main()
{
SqStack S;
InitStack(S);
char t[]="abba";
printf("该字符序列是否是回文序列? %d(1:是 0:否) ",HuiWen(t));
}