數據結構隊列實例


  1 //數據結構 --隊列
  2 //靜態隊列-用數組實現
  3 //靜態隊列通常是循環隊列
  4 //循環隊列講解
  5 //1.靜態隊列為什么必須是循環隊列?
  6 //2.循環隊列需要幾個參數來確定?
  7 /*
  8     front 和 rear
  9     1)隊列初始化,font和rear的值都為零
 10     2)隊列非空   
 11         font代表的是隊列的第一個元素
 12         rear代表的是隊列的最后一個有效元素的下一個元素
 13     3)隊列空
 14         front和rear值
 15 */
 16 //3.循環隊列各個參數的含義?
 17 //4.如何判斷循環隊列是否為空?
 18 /*
 19     front與rear值相等,則該隊列就一定為空;
 20 */
 21 //5.如何判斷循環隊列是否已滿?
 22 /*
 23 1)利用標志參數來判定是否已滿;
 24 2)少用一個元素
 25 if((r+1)%數組長度==f)
 26     已滿;
 27 else
 28     不滿;
 29 */
 30 //6.循環隊列入隊偽算法講解
 31 #include <stdio.h>
 32 
 33 typedef struct Queue
 34 {
 35     int *pBase;
 36     int front;
 37     int rear;
 38 }QUEUE;
 39 
 40 void init(QUEUE*);
 41 bool en_queue(QUEUE*, int val);
 42 void traverse_queue(QUEUE);
 43 bool out_queue(QUEUE*, int *);
 44 bool empty_queue(QUEUE* pQ);
 45 
 46 int main(void)
 47 {
 48     QUEUE Q;
 49     en_queue(&Q, 1);
 50     en_queue(&Q, 1);
 51     en_queue(&Q, 1);
 52     init(&Q);
 53     return 0;
 54 }
 55 
 56 void init(QUEUE *pQ)
 57 {
 58     pQ->pBase = (int*)malloc(sizeof(int)*6);
 59     pQ->front = 0;
 60     pQ->rear = 0;
 61 }
 62 
 63 bool en_queue(QUEUE* pQ, int val)
 64 {
 65     if (full_queue(pQ))
 66     {
 67         return false;
 68     }
 69     else
 70     {
 71         pQ->pBase[pQ->rear] = val;
 72         pQ->rear = (pQ->rear + 1)%6;
 73         return true;
 74     }
 75 }
 76 
 77 bool full_queue(QUEUE *pQ)
 78 {
 79     if (pQ->front == (pQ->rear + 1) % 6)
 80     {
 81         return true;
 82     }
 83     else
 84     {
 85         return false;
 86     }
 87 }
 88 
 89 void traverse_queue(QUEUE *pQ)
 90 {
 91     int i = pQ->front;
 92     while (i != pQ->rear)
 93     {
 94         printf("%d",pQ->pBase[i]);
 95         i = (i + 1) % 6;
 96     }
 97     return;
 98 }
 99 
100 bool empty_queue(QUEUE *pQ)
101 {
102     if (pQ->rear == pQ->front)
103     {
104         return true;
105     }
106     else
107     {
108         return false;
109     }
110 }
111 
112 bool out_queue(QUEUE*pQ, int* pVal)
113 {
114     if (empty_queue(pQ))
115     {
116         return false;
117     }
118 
119     int i = 0;
120     while (i != pQ->rear)
121     {
122         *pVal = pQ->pBase[pQ->front];
123         pQ->front = (pQ->front + 1) % 6;
124     }
125     return true;
126 }
127 
128 //隊列的具體應用:所有和時間有關的都與隊列有關

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM