天天看點

循環隊列(數組實作)

循環隊列(數組實作)
1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define false 0
 5 #define true 1
 6 
 7 typedef int ElementType;
 8 typedef int Position;
 9 typedef int bool;
10 typedef struct QNode *PtrToQNode;
11 struct QNode
12 {
13    ElementType *Data;
14    Position Front,Rear;
15    int MaxSize;
16 };
17 typedef PtrToQNode Queue;
18 
19 Queue CreateQueue(int MaxSize);   //建立一個最大長度為MaxSize的空隊列
20 bool IsFull(Queue Q);   //判斷隊列是否已滿
21 bool IsEmpty(Queue Q);  //判斷隊列是否為空
22 bool AddQ(Queue Q, ElementType X);    //入隊
23 ElementType DeleteQ(Queue Q);         //出隊
24 
25 
26 
27 Queue CreateQueue(int MaxSize)
28 {
29     Queue Q = (Queue)malloc(sizeof(struct QNode));
30     Q->Data = (ElementType *)malloc(MaxSize*sizeof(ElementType));
31     Q->Front = Q->Rear = 0;
32     Q->MaxSize = MaxSize;
33     return Q;
34 }
35 
36 bool IsFull(Queue Q)
37 {
38     return ((Q->Rear+1) % (Q->MaxSize)) == Q->Front;
39 }
40 
41 bool IsEmpty(Queue Q)
42 {
43     return Q->Front == Q->Rear;
44 }
45 
46 bool AddQ(Queue Q, ElementType X)
47 {
48     if(IsFull(Q))
49     {
50         printf("隊列已滿,無法入隊!\n");
51         return false;
52     }
53     Q->Rear = (Q->Rear+1)%(Q->MaxSize);
54     Q->Data[Q->Rear] = X;
55     return true;
56 }
57 
58 ElementType DeleteQ(Queue Q)
59 {
60     if(IsEmpty(Q))
61     {
62         printf("隊列為空,無法出隊!\n");
63         return false;
64     }
65     Q->Front = (Q->Front+1)%(Q->MaxSize);
66     return Q->Data[Q->Front];
67 }