用栈和队列实现判断是否是回文序列

用栈和队列实现判断是否是回文序列

在学习了栈和队列之后,为加强对栈和队列的熟练运用,特此运用栈和队列进行回文判断。虽然很麻烦,本来一个for循环就能解决的问题,但是增强了对栈和队列的理解和运用,还是值得一试的。
本代码实现所需功能所需要理解的是栈有后进先出、队列是先进先出的特点,并掌握入队、入栈、出队、出栈的函数实现。
`//整体思路:利用栈的后进先出和队列的先进先出的特点,将一个数组序列分别输入队列和栈中,然后分别依次弹出每个元素,如果每次弹出的都相同,则是回文序列,否则不是 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct SeqQueue
{
int max;
int front;
int rear;
char *dui;
};
typedef struct SeqQueue PSeqQueue;
PSeqQueue createEmptyQueue_seq(int m) //创建队列
{
PSeqQueue q=(PSeqQueue)malloc(sizeof(PSeqQueue));
if(q!=NULL)
{
q->dui=(char
)malloc(sizeof(char)*m);
if(q->dui)
{
q->max=m;
q->front=0;
q->rear=0;
return q;
}
}
else free(q);
printf(“out of space!”);
return NULL;
}
int isEmptyQueue(PSeqQueue p) //判断是否为空队列,若是空队列,返回0 ,有最好,无也行
{
if(p->front==p->rear) return 0;
else return 1;
}
void enQueue_seq(PSeqQueue p,char x) //入队
{
if((p->rear)==p->max) printf(“Full Queue\n”);
else
{
p->dui[p->rear]=x;
p->rear=(p->rear+1)%(p->max);
}
}
char deQueue_seq(PSeqQueue p) //出队
{

	int a=p->front;
	p->front=(p->front+1)%(p->max);
	return(p->dui[a]);

}

struct seqStack
{
int max;
int t;
char *s;
};
typedef struct seqStack PSeqStack;
PSeqStack createEmptyStack(int m) //开始创建栈
{
PSeqStack q=(PSeqStack)malloc(sizeof(char));
if(q!=NULL)
{
q->s=(char
)malloc(sizeof(char)*m);
q->t=-1;
return q;
}
else {
free(q);
printf(“failed”);
return NULL;
}
}
void push_seq(PSeqStack p,char x)
{
if(p->t>=(p->max)-1) printf(“overflow”);
else {
p->t+=1;
p->s[p->t]=x;
}
}
char pop_seq(PSeqStack p)
{
if(p->t==-1) printf(“underflow”);
else {
int a=p->t;
p->t=p->t-1;
return(p->s[a]);
}
}
int isEmptyStack(PSeqStack p)
{
if(p->t=-1) return 0;
else return 1;
}
int main()
{
char str[50];
printf(“请输入一个字符串:\n”);
gets(str);
int m=strlen(str);
PSeqQueue duilie=createEmptyQueue_seq(m);
PSeqStack zhan=createEmptyStack(m);
int i,j;
for(i=0;i<m;i++) //将数组str的元素入队和入栈
{
enQueue_seq(duilie,str[i]);
push_seq(zhan,str[i]);
}
for(i=0;i<m;i++) //将数组str的元素出队和出栈,同时判断输出的元素是否相同
{
char a=deQueue_seq(duilie);
char b=pop_seq(zhan);
if(a!=b)
{
printf(“不是回文序列!”);
return 0;
}
}
printf(“是回文序列!”);
return 0;
}`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值