每天一個數據結構----佇列的順序儲存結構實現(純程式碼)
阿新 • • 發佈:2018-12-20
// // main.c // Queue 迴圈佇列 // // // Created by Jacobs.Guo on 2018/5/7. // Copyright © 2018年 yage guo. All rights reserved. // #include <stdio.h> #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 10 typedef int Status; typedef int QElemType; typedef struct { QElemType data[MAXSIZE]; int head; int tail; }Queue; //初始化佇列 Status InitQueue(Queue *Q) { Q->head = 0; Q->tail = 0; return OK; } //佇列是否已經滿員 Status FullQueue(Queue *Q) { if ( (Q->tail+1)%MAXSIZE == Q->head ) return OK; else return FALSE; } //入佇列操作 Status EnQueue(Queue *Q,QElemType e) { if (FullQueue(Q)) return ERROR; Q->data[Q->tail] = e; Q->tail = (Q->tail+1)%MAXSIZE; return OK; } //佇列長度 int LengthQueue(Queue Q) { return (Q.tail-Q.head+MAXSIZE)%MAXSIZE; } //出佇列操作 Status DeQueue(Queue *Q,QElemType *e) { if (Q->head == Q->tail) return ERROR; *e = Q->data[Q->head]; Q->head = (Q->head+1)%MAXSIZE; return OK; } int main() { Queue Q; int i;QElemType e; printf("初始化佇列Q...\n"); InitQueue(&Q); if (FullQueue(&Q)) printf("佇列Q為空...\n"); else printf("佇列Q非空...\n"); printf("佇列Q的長度為:%d\n",LengthQueue(Q)); printf("將1 2 3 4 5 做順序入佇列操作...\n"); for (i = 0;i<5;i++) { EnQueue(&Q,i+1); } printf("佇列Q的長度為:%d\n",LengthQueue(Q)); DeQueue(&Q, &e); printf("%d已經出佇列...\n",e); return 0; }