#include <stdio.h>
#include <stdlib.h>
#define Stack_Init_Size 10 // 初始化栈的最大长度
#define MAXQSIZE 100 // 初始化队列的最大长度
typedef char ElemType;
typedef char QElemType;
typedef struct {
ElemType *base; // 栈底指针
ElemType *top; // 栈顶指针
int stacksize; // 栈的最大长度
} SqStack;
// 初始化栈
InitStack(SqStack &S) {
// 分配初始空间
S.base = (ElemType *) malloc(Stack_Init_Size * sizeof(ElemType));
if (!S.base) {
exit(0);
}
S.top = S.base; /// 栈顶与栈底相同
S.stacksize = Stack_Init_Size; // 栈的最大长度等于初始长度
return 1;
}
// 判断栈是否为空,只需要判断栈顶指针与栈底指针是否相同即可
EmptyStack(SqStack &S) {
return S.base == S.top;
}
// 进栈,参数e是要进栈的元素
Push(SqStack &S, ElemType e) {
if (S.top - S.base == S.stacksize)
return 0;
*S.top++ = e; // 先赋值,后栈顶指针上移
return 1;
}
// 出栈,参数e用来存放出栈的元素
Pop(SqStack &S, ElemType &e) {
if (S.base == S.top) {
return 0;
}
e = *--S.top; // 栈顶指针先下移,后赋值
return 1;
}
typedef struct {
QElemType *base;
int front; //头指针
int rear; //尾指针
} SqQueue;
//初始化队列
InitQueue(SqQueue &Q) {
Q.base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType)) ;
if(!Q.base) {
exit(0);
}
Q.front=Q.rear=0;
return 1;
}
//入队
EnQueue(SqQueue &Q,QElemType e) {
if((Q.rear+1)%MAXQSIZE==Q.front)
return -1;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
return 1;
}
//出队
DeQueue(SqQueue &Q,QElemType &e) {
if(Q.front==Q.rear) return -1;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXQSIZE;
return 1;
}
//获得队列长度
QueueLength(SqQueue &Q) {
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
//判断队列是否为空
QueueEmpty(SqQueue &Q) {
if(Q.front==Q.rear) return 1;
else return 0;
}
//判断字符串是否回文
judge() {
SqStack S;
SqQueue Q;
char a,b,c;
InitStack(S);
InitQueue(Q);
printf("输入字符串,以'@'结束:\n");
while((a=getchar())!='@') {
Push(S,a);
EnQueue(Q,a);
}
int len = QueueLength(Q);
while(!QueueEmpty(Q)&&(!EmptyStack(S))) {
for(int i=0; i<len/2; i++) {
Pop(S,b);
DeQueue(Q,c);
}
if(b!=c) {
return 0;
}
else {
return 1;
}
}
}
//主函数
int main() {
printf("判断回文\n");
if(judge()) {
printf("是回文");
}
else {
printf("不是回文");
}
return 0;
}
C语言判断回文
于 2023-10-27 20:29:49 首次发布