資料結構-C語言實現迴圈佇列
阿新 • • 發佈:2018-12-21
#include<stdio.h> #include<stdlib.h> #define MAXSIZE 100 #define OK 1 #define OVERFLOW -1 typedef struct{ int *base; int front; int rear; }SqQueue; typedef int Status; //初始化 Status InitQueue(SqQueue *Q) { Q->base=(int *)malloc(MAXSIZE*sizeof(int)); if(!(Q->base)) exit(OVERFLOW); Q->front=Q->rear=0; return OK; } //佇列的長度 int QueueLength(SqQueue Q) { return (Q.rear-Q.front+MAXSIZE)%MAXSIZE; } //入隊 Status EnQueue(SqQueue *Q,int e) { if((Q->rear+1)%MAXSIZE==Q->front) return -1; Q->base[Q->rear]=e; Q->rear=(Q->rear+1)%MAXSIZE; return OK; } //出隊 Status DeQueue(SqQueue *Q,int *e) { if(Q->front==Q->rear) return -1; *e=Q->base[Q->front]; Q->front=(Q->front+1)%MAXSIZE; return OK; } void main() { int ch=1; SqQueue Q; InitQueue(&Q); while(ch!=0) { system("cls"); printf("1.佇列長度\t2.進隊\t3.出隊\n"); printf("請選擇:\n"); scanf("%d",&ch); switch(ch) { case 0:printf("byebye!\n"); break; case 1: { int len; len=QueueLength(Q); printf("長度為:%d\n",len); break; } case 2: { int e; printf("請輸入你要入隊的數值:\n"); scanf("%d",&e); if(EnQueue(&Q,e)==OK) printf("入隊成功\n"); else printf("入隊失敗\n"); break; } case 3: { int e; DeQueue(&Q,&e); printf("%d\n",e); break; } default: printf("輸入錯誤,請重新輸入\n"); break; } system("pause"); } }