1 /*
2 * 五、数据结构基础之循环队列
3 * 循环队列数据结构:
4 * 由于入队和出队操作中,头指针和尾指针只会增加,导致假上溢而不能有效地利用队列空间
5 * 将队列空间想象为一个首尾相连的圆环,以此来克服顺序队列的假上溢现象
6 * --- 2012年4月28日 ---by lee
7 */
8
9 #ifndef _CIRCULAR_QUEUE_H
10 #define _CIRCULAR_QUEUE_H
11
12 #include "Utility.h"
13
14 //宏定义循环队列的空间大小
15 #define QUEUESIZE 20
16
17 //元素类型定义
18 typedef int DataType;
19
20 //循环队列结构的定义
21 typedef struct _CircularQueue
22 {
23 int front; //队列头指针
24 int rear; //队列尾指针
25 int count; //计数器,统计队列中元素个数
26 DataType data[QUEUESIZE]; //存储队列中的元素
27 } CircularQueue;
28
29 //对循环队列(顺序队列)的基本操作
30
31 void InitQueue(CircularQueue* queue);//初始化,构造空队
32 int IsQueueEmpty(CircularQueue* queue);//判断队是否为空
33 int IsQueueFull(CircularQueue* queue);//判断队是否为满,仅针对顺序队列
34 void EnQueue(CircularQueue* queue, DataType x);//元素x入队
35 DataType DeQueue(CircularQueue* queue);//出队,返回队首元素
36 DataType QueueFront(CircularQueue* queue);//取队首元素
37
38 //初始化,构造空队
39 void InitQueue(CircularQueue* queue)
40 {
41 queue->front=queue->rear=0;
42 queue->count=0;
43 }
44
45 //队列为空和满时,front都等于rear;判断队列是否为空或者为满:
46 //1、使用计数器count
47 //2、少用一个元素的空间,约定队列满时:(rear+1)%QUEUESIZE=front
48 //rear指向队尾元素的下一个位置,始终为空;队列的长度为(rear-front+QUEUESIZE)%QUEUESIZE
49
50 //判断队是否为空
51 int IsQueueEmpty(CircularQueue* queue)
52 {
53 return (0==queue->count);
54 }
55
56 //判断队是否为满
57 int IsQueueFull(CircularQueue* queue)
58 {
59 return (QUEUESIZE==queue->count);
60 }
61
62 //元素x入队
63 void EnQueue(CircularQueue* queue, DataType x)
64 {
65 //入队前,判断队满
66 if(IsQueueFull(queue))
67 Error("Queue is full");
68
69 queue->data[queue->rear]=x;
70 queue->rear=(queue->rear+1)%QUEUESIZE;
71 queue->count++;
72 }
73
74 //出队,返回队首元素
75 DataType DeQueue(CircularQueue* queue)
76 {
77 //出队前,判断队空
78 if(IsQueueEmpty(queue))
79 Error("Queue is empty");
80
81 DataType ret=queue->data[queue->front];
82 queue->front=(queue->front+1)%QUEUESIZE;
83 queue->count--;
84 return ret;
85 }
86
87 //取队首元素
88 DataType QueueFront(CircularQueue* queue)
89 {
90 //判断队空
91 if(IsQueueEmpty(queue))
92 Error("Queue is empty");
93
94 return queue->data[queue->front];
95 }
96
97
98 #endif
99
100 //测试代码
101 /*
102 CircularQueue q;
103 InitQueue(&q);
104 EnQueue(&q,1);
105 EnQueue(&q,2);
106 printf("Queue Front: %d\n",DeQueue(&q));
107 printf("Queue Front: %d\n",DeQueue(&q));
108 EnQueue(&q,1);
109 EnQueue(&q,2);
110 printf("Queue length: %d\n",q.count);
111 */