隊頭指針在隊尾指針的下一位置時,隊滿。 Q.front == (Q.rear + 1) % MAXSIZE 因為隊頭指針可能又重新從0位置開始,而此時隊尾指針是MAXSIZE - 1,所以需要求余。
當隊頭和隊尾指針在同一位置時,隊空。 Q.front == Q.rear;
1 #include <stdio.h> 2 #include <malloc.h> 3 #define MAXSIZE 100 //最大隊列長度 4 #define OK 1 5 #define ERROR 0 6 typedef int ElemType; 7 typedef int Status; 8 9 typedef struct { 10 ElemType *base; //隊列空間 11 int front; //隊頭指針 12 int rear; //隊尾指針,若隊尾不為空,則指向隊尾元素的下一個位置 13 }SqQueue; 14 15 //初始化循環隊列 16 Status initQueue(SqQueue &Q) { 17 Q.base = (ElemType *) malloc(MAXSIZE * sizeof(ElemType)); //申請空間 18 Q.front = Q.rear = 0; //隊空 19 return OK; 20 } 21 22 //入隊 23 Status enQueue(SqQueue &Q, ElemType e) { 24 if ((Q.rear + 1) % MAXSIZE == Q.front) return ERROR; //隊滿,無法添加 25 Q.base[Q.rear] = e; //插入元素 26 Q.rear = (Q.rear + 1) % MAXSIZE; //隊尾指針+1 27 return OK; 28 } 29 30 //出隊 31 Status deQueue(SqQueue &Q, ElemType &e) { 32 if (Q.front == Q.rear) return ERROR; //隊空,無法刪除 33 e = Q.base[Q.front]; 34 Q.front = (Q.front + 1) % MAXSIZE; //隊頭指針+1 35 return OK; 36 } 37 38 //返回隊列長度 39 Status length(SqQueue &Q) { 40 return (Q.rear - Q.front + MAXSIZE) % MAXSIZE; 41 } 42 ———————————————— 43 版權聲明:本文為CSDN博主「this.」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。 44 原文鏈接:https://blog.csdn.net/u010429311/article/details/51043149