C语言用栈和队列实现的回文检测功能示例
时间:2021-02-01 09:58:56|栏目:C代码|点击: 次
本文实例讲述了C语言用栈和队列实现的回文功能。分享给大家供大家参考,具体如下:
#include<stdio.h> #include<malloc.h>//内存分配头文件 #include<math.h>//在math.h中已定义OVERFLOW的值为3 #define SIZE 100 #define STACKINCREMENT 10 #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 typedef int Status; typedef struct //栈的结构体 { char a; } SElemType; typedef struct { SElemType *base; SElemType *top; int stacksize; } SqStack; typedef struct //QNode //队列的结构体 { char b; struct QNode * next; } QNode,*QueuePtr; typedef struct // 链队列类型 { QueuePtr front; // 队头指针 QueuePtr rear; // 队尾指针 } LinkQueue; //定义全局变量 SqStack S; SElemType e; LinkQueue Q; QueuePtr p; char f; //栈操作 Status InitStack(SqStack *S) { S->base=(SElemType *)malloc(SIZE*sizeof(SElemType)); if(!S->base) exit(OVERFLOW); S->top=S->base; S->stacksize=SIZE; return OK; } Status Push(SqStack *S,SElemType e) { if(S->top-S->base>=S->stacksize) { S->base=(SElemType *)malloc((S->stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S->base) exit(OVERFLOW); S->top=S->base+S->stacksize; S->stacksize+=STACKINCREMENT; } *S->top++=e; return OK; } Status Stackempty(SqStack S)//栈是否为空 { if(S.top==S.base) return TRUE; else return FALSE; } Status Pop(SqStack *S,SElemType *e) { if(S->top==S->base) return ERROR; *e=*--S->top; return OK; } Status StackLength(SqStack S)//求栈的长度 { return (S.top-S.base); } //队列操作 Status InitQueue(LinkQueue *Q) { Q->front=(QueuePtr)malloc(sizeof(QNode)); Q->rear=Q->front; if(!Q->front) exit(OVERFLOW); Q->front->next=NULL; return OK; } Status EnQueue(LinkQueue *Q,char f) { p=(QueuePtr)malloc(sizeof(QNode)); if(!p) exit(OVERFLOW); p->b=f; p->next=NULL; Q->rear->next=p; Q->rear=p; return OK; } Status DeQueue(LinkQueue *Q,char *f) { if(Q->front==Q->rear) return ERROR; p=Q->front->next; *f=p->b; Q->front->next=p->next; if(Q->rear==p) Q->rear=Q->front; free(p); return OK; } Status QueueLength(LinkQueue Q) { int i=0; p=Q.front; while(Q.rear!=p) { i++; p=p->next; } return i; } Status QueueEmpty(LinkQueue Q) { if(Q.front==Q.rear) return TRUE; else return FALSE; } void main() { int i,m; char n,a[20]; InitStack(&S); InitQueue(&Q); gets(a); for(i=0; a[i]!='&'; i++) /////////// &前的数据进栈 { e.a=a[i]; Push(&S,e); } for(i=i+1; a[i]!='\0'; i++) ////////// ‘ &'后的数据进入队列 EnQueue(&Q,a[i]); if( StackLength(S)!=QueueLength(Q)) /////栈和队列的数据个数不一样 printf("NO!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); else while(!Stackempty(S)&&!QueueEmpty(Q))///////栈和队列里还有数据 { Pop(&S,&e); m=e.a; DeQueue(&Q,&f); n=f; if(m!=n) { printf("NO!!!!!!!!!!!!!!!!!!!!!!"); break; } } if(m==n&&Stackempty(S)&&QueueEmpty(Q)) printf("YES!!!!!!!!!!!!!!!!!!!!!!"); }
运行结果:
希望本文所述对大家C语言程序设计有所帮助。