问题:假设正读和反读都相同的字符序列为“回文”,例如,‘abba’和‘abcba’是回文,‘abcde’ 和‘ababab’则不是回文。试写一个算法判别读入的一个以‘@’为结束符的字符序列是否是“回文”。
#include <stdio.h>
#include<stdlib.h>
#define m 100
typedef struct //定义栈
{
char data[m];
int top;
}stack;
typedef struct { //定义队列
char data[m];
int front;
int rear;
}Queque;
void InitStack(stack *s) //初始化栈
{
s->top=0;
}
void InitQueque(Queque *q) //初始化队列
{
q->front=q->rear=0;
}
int StackEmpty(stack *s) //判断栈是否为空
{
if(s->top==0)
{
return 0;
}
else
{
return 1;
}
}
void Push(stack *s,charx) //入栈
{
if(s->top==m)
{
printf("Stack Empty!\n");
}
else
{
s->data[++s->top]=x;
}
}
char OutStack(stack *s) //出栈
{
char y;
if(s->top==0)
{
printf("Stack Empty!\n");
return '0';
}
else
{
y=s->data[s->top];
s->top=s->top-1;
return y;
}
}
void EnterQueque(Queque *q,chare) //入队
{
if((q->rear+1)%m==q->front)
{
printf("The queque isempty\n");
}
else
{
q->data[q->rear]=e;
q->rear=(q->rear+1);
}
}
char OutQueque(Queque *q) //出队
{
char f;
if(q->front==q->rear)
{
printf("The queque isempty\n");
return 0;
}
else
{
f=q->data[q->front];
q->front=(q->front+1);
return f;
}
}
int main()
{
char c;
int flag=0;
stack *s=(stack *)malloc(sizeof(stack));
Queque *q=(Queque *)malloc(sizeof(Queque));
InitStack(s);
InitQueque(q);
printf("Please enter astring:\n");
while((c=getchar())!='@')
{
Push(s,c);
EnterQueque(q,c);
}
while(StackEmpty(s))
{
if(OutStack(s)== OutQueque(q))
{
flag=1;
continue;
}
else
{
flag=0;
break;
}
}
if(flag==1)
printf("This string is palindrome\n");
else
printf("This string is notpalindrome\n");
return 0;
}
运行结果如下所示: