#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;
#define MAXQSIZE 100
typedef struct {
ElemType *base;
int front;
int rear;
} SqQueue;
typedef struct
{ ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
SqStack InitStack(SqStack S)
{ S.base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if (!S.base) printf("空间分配失败\n");
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return S;
}
void Push(SqStack *S, ElemType e)
{
if (S->top-S->base>=S->stacksize)
{
S->base = (ElemType *) realloc (S->base,(S->stacksize + STACKINCREMENT)*sizeof (ElemType));
if (!S->base) printf("空间分配失败\n");
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top++) = e;
}
ElemType GetTop(SqStack *S)
{
if ((*S).top==(*S).base) printf("栈是空的\n");
ElemType e;
e=*((*S).top-1);
(*S).top--;
return e;
}
SqQueue InitQueue (SqQueue Q)
{
Q.base = (ElemType *) malloc(MAXQSIZE *sizeof (ElemType));
if (!Q.base) printf("空间分配失败!\n");
Q.front=0;
Q.rear=0;
return Q;
}
void EnQueue(SqQueue *Q,ElemType e)
{
if (((*Q).rear+1) % MAXQSIZE==(*Q).front)
printf("队列已满!\n");
(*Q).base[(*Q).rear] = e;
(*Q).rear = ((*Q).rear+1) % MAXQSIZE;
}
ElemType DeQueue (SqQueue *Q)
{
ElemType e;
if (Q->front==Q->rear)
printf("队列空!\n");
e=Q->base[Q->front];
Q->front = (Q->front+1) % MAXQSIZE;
return e;
}
void huiwen()
{ SqQueue Q,Q1;SqStack S,S1;
Q1=InitQueue(Q);
S1=InitStack(S);
ElemType c;
scanf("%c",&c);
while(c!='#')
{
EnQueue(&Q1,c);
Push(&S1,c);
scanf("%c",&c);
}
while(Q1.front!=Q1.rear && S1.top!=S1.base)
{ if(GetTop(&S1)==DeQueue(&Q1))
continue;
else { printf("不是回文!\n");break;}}
if(Q1.front==Q1.rear && S1.top==S1.base)
printf("是回文!\n");
}
void main()
{
printf("请输入字符串,以'#'结束!\n");
huiwen();
}
数据结构:用栈和队列判断是否回文c++
最新推荐文章于 2023-10-17 23:27:25 发布