————————————————————————————————————————————
如果使用順序表作為隊列的話,當處於右圖狀態則不能繼續插入新的隊尾元素,否則會因為數組越界而導致程序代碼被破壞。
由此產生了由鏈表實現的循環隊列,只有隊列未滿時才可以插入新的隊尾元素。
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
基本操作:
/* 定義鏈表隊列 */
定義結構體中front指示隊頭位置,rear指示隊尾位置,base指針用於申請空間並存放數據。
/* 初始化隊列 */
使用指針*base申請100個內存空間,front和rear分別為0,此時隊列為空
/* 判斷空或滿 */
-
初始化時, front = rear = 0 時為空, Q->rear = ( 0+1 ) %100 = 1 ,隊列未滿可以插入隊列
-
入隊 3 個元素時, rear = 3 , Q->rear = ( 3+1 ) %100 = 4 ,隊列未滿
-
入隊 99 個元素時, rear = 99 , Q->rear = ( 99+1 ) %100 = 0 ,隊列滿,不可入隊
-
出隊 2 個元素時, front = 2
出隊后,執行兩次 Q->front = (Q->front + 1) % MAXQSIZE,得到Q->front = 2
-
再次入隊 1 個元素時, rear = 0 , Q->rear = ( 99+1 ) %100=0 ,隊列未滿,可以入隊
實現代碼:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define OK 1 4 #define ERROR 0 5 #define OVERFLOW -2 6 #define MAXQSIZE 100 7 typedef int Status; 8 typedef int QElemType; 9 typedef struct Node 10 { 11 QElemType *base; //初始化動態分配存儲空間 12 int front; 13 int rear; 14 } SqQueue; 15 Status InitQueue(SqQueue *Q) 16 { 17 Q->base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType)); 18 if (!Q->base) 19 exit(OVERFLOW); 20 Q->front = Q->rear = 0; 21 return OK; 22 } 23 Status EnQueue(SqQueue *Q, QElemType elem) 24 { 25 //隊列為空時 1%100==1,隊列滿時(99+1)%100==0,最多容納99個元素 26 if ((Q->rear + 1) % MAXQSIZE == (Q->front)) 27 return ERROR; 28 Q->base[Q->rear] = elem; 29 Q->rear = (Q->rear + 1) % MAXQSIZE; //rear始終在0-100中循環 30 return OK; 31 } 32 Status OutQueue(SqQueue *Q, QElemType *e) 33 { 34 if (Q->front == Q->rear) 35 return ERROR; 36 *e = Q->base[Q->front]; 37 Q->front = (Q->front + 1) % MAXQSIZE; 38 return OK; 39 } 40 Status PrintQueue(SqQueue Q) 41 { 42 printf("the queue is:"); 43 for (int i = Q.front; i < Q.rear; ++i) 44 printf("%d ", Q.base[i]); 45 return OK; 46 } 47 int main() 48 { 49 SqQueue queue; 50 QElemType elem; 51 int i; 52 InitQueue(&queue); 53 printf("input:"); 54 while(scanf("%d", &elem) != EOF) 55 EnQueue(&queue, elem); 56 PrintQueue(queue); 57 /* 輸入要出隊列的個數 */ 58 printf("\noutput:"); 59 scanf("%d", &i); 60 while(i != 0) 61 { 62 OutQueue(&queue, &elem); 63 i--; 64 } 65 PrintQueue(queue); 66 return OK; 67 }