數據結構——循環隊列操作

複製代碼
  1 /*  2 循環隊列的基本操作,初始化,入隊,遍歷,出隊等操作
  3 */  4 #include <stdio.h>  5 #include <malloc.h>  6   7 #define true 1  8 #define false 0  9  10 typedef struct Queue
 11 {
 12     int *pBase;     //定義數組pBase 13     int front;
 14     int rear;
 15 }QUEUE;
 16  17 void init(QUEUE *pQ);
 18 int en_queue(QUEUE *pQ , int val);
 19 void traverse_queue(QUEUE *pQ);
 20 int out_queue(QUEUE *pQ , int *pVal);
 21  22 int main(void)
 23 {
 24     QUEUE Q;
 25     int val;
 26  27     init(&Q);
 28  29     en_queue(&Q,1);
 30     en_queue(&Q,2);
 31     en_queue(&Q,3);
 32     en_queue(&Q,4);
 33     en_queue(&Q,5);
 34     en_queue(&Q,6);
 35     en_queue(&Q,7);
 36     en_queue(&Q,8);
 37  38     traverse_queue(&Q);
 39  40     if(out_queue(&Q,&val))
 41     {
 42         printf("出隊成功,隊列出隊元素爲 : %d\n",val);
 43     }
 44     else 45     {
 46         printf("出隊失敗!");
 47     }
 48  49     traverse_queue(&Q);
 50  51     return 0;
 52 }
 53  54 //循環隊列的初始化 55 void init(QUEUE *pQ)
 56 {
 57     pQ -> pBase = (int *)malloc(sizeof(int)*6);   //分配內存,數組長度爲6 58  59     pQ -> front = 0;                              
 60     pQ -> rear = 0;
 61  62     return;
 63 }
 64  65 //判斷循環隊列是否爲滿 66 int full_queue(QUEUE *pQ)
 67 {
 68     if((pQ -> rear + 1) % 6 == pQ -> front)     
 69     {
 70         return true;
 71     }
 72     else 73         return false;
 74 }
 75  76 //入隊操作 77 int en_queue(QUEUE *pQ , int val)
 78 {
 79     if(full_queue(pQ))
 80     {
 81         return false;
 82     }
 83     else 84     {
 85         pQ -> pBase[pQ -> rear] = val;
 86         pQ -> rear = (pQ -> rear + 1) % 6;
 87  88         return true;
 89     }
 90 }
 91  92  93 //遍歷循環隊列 94 void traverse_queue(QUEUE *pQ)
 95 {
 96     int i = pQ -> front;
 97  98     printf("遍歷隊列:");
 99     while(i != pQ -> rear)
100     {
101         printf("%d\t", pQ -> pBase[i]);
102 103         i = (i + 1) % 6 ;
104     }
105 106     printf("\n");
107 108     return;
109 }
110 111 //判斷循環隊列是否爲空112 int empty_queue(QUEUE *pQ)
113 {
114     if(pQ -> front == pQ -> rear)
115     {
116         return true;
117     }
118     else119         return false;
120 }
121 122 //循環隊列的出隊操作123 int out_queue(QUEUE *pQ , int *pVal)
124 {
125     if(empty_queue(pQ))
126     {
127         return false;
128     }
129     else130     {
131         *pVal = pQ -> pBase[pQ -> front];
132         pQ -> front = (pQ -> front + 1) % 6;
133 134         return true;
135     }
136 }
複製代碼

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章