C語言用棧和隊列實現的回文檢測功能示例。本站提示廣大學習愛好者:(C語言用棧和隊列實現的回文檢測功能示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C語言用棧和隊列實現的回文檢測功能示例正文
作者:PHP開發學習門戶
這篇文章主要介紹了C語言用棧和隊列實現的回文檢測功能,結合具體實例形式分析了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語言程序設計有所幫助。