循环队列基本操作
1 #ifndef _CIRCULAR_QUEUE_H 2 #define _CIRCULAR_QUEUE_H 3 #include <cstdio> 4 5 //循环队列的最大空间大小 6 #define QUEUESIZE 20 7 #define OK 1 8 #define QUEUE_FULL -1 9 #define QUEUE_EMPTY -2 10 11 //元素类型定义 12 typedef int DataType; 13 14 /***********************循环队列结构的定义*******************************************/ 15 typedef struct _CircularQueue 16 { 17 int front; //队列头指针 18 int rear; //队列尾指针 19 int count; //计数器,统计队列中元素个数 20 DataType data[QUEUESIZE]; //存储队列中的元素 21 } CircularQueue; 22 23 //对循环队列(顺序队列)的基本操作 24 void InitQueue(CircularQueue* queue); //初始化,构造空队 25 int IsQueueEmpty(CircularQueue* queue); //判断队是否为空 26 int IsQueueFull(CircularQueue* queue); //判断队是否为满,仅针对顺序队列 27 int EnQueue(CircularQueue* queue, DataType x); //元素x入队 28 DataType DeQueue(CircularQueue* queue); //出队,返回队首元素 29 DataType QueueFront(CircularQueue* queue); //取队首元素 30 31 //初始化空队列 32 void InitQueue(CircularQueue* queue) 33 { 34 queue->front = queue->rear=0; 35 queue->count = 0; 36 } 37 38 //队列为空和满时,front都等于rear;判断队列是否为空或者为满: 39 //1、使用计数器count 40 //2、少用一个元素的空间,约定队列满时:(rear+1)%QUEUESIZE=front 41 //rear指向队尾元素的下一个位置,始终为空;队列的长度为(rear-front+QUEUESIZE)%QUEUESIZE 42 43 //判断队是否为空 44 int IsQueueEmpty(CircularQueue* queue) 45 { 46 return (0 == queue->count); 47 } 48 49 //判断队是否为满 50 int IsQueueFull(CircularQueue* queue) 51 { 52 return (QUEUESIZE == queue->count); 53 } 54 55 //元素x入队 56 int EnQueue(CircularQueue* queue, DataType x) 57 { 58 //入队前,判断队满 59 if(IsQueueFull(queue)) 60 { 61 return QUEUE_FULL; 62 } 63 queue->data[queue->rear]=x; 64 queue->rear=(queue->rear+1)%QUEUESIZE; 65 queue->count++; 66 return OK; 67 } 68 69 //出队,返回队首元素 70 DataType DeQueue(CircularQueue* queue) 71 { 72 //出队前,判断队空 73 if(IsQueueEmpty(queue)) 74 { 75 return QUEUE_EMPTY; 76 } 77 DataType ret = queue->data[queue->front]; 78 queue->front = (queue->front+1)%QUEUESIZE; 79 queue->count--; 80 return ret; 81 } 82 83 //取队首元素 84 DataType QueueFront(CircularQueue* queue) 85 { 86 //判断队空 87 if(IsQueueEmpty(queue)) 88 { 89 return QUEUE_EMPTY; 90 } 91 return queue->data[queue->front]; 92 } 93 94 #endif 95 96 //测试代码 97 int main() 98 { 99 CircularQueue q; 100 InitQueue(&q); 101 EnQueue(&q,1); 102 EnQueue(&q,2); 103 printf("Queue Front: %d\n",DeQueue(&q)); 104 printf("Queue Front: %d\n",DeQueue(&q)); 105 EnQueue(&q,1); 106 EnQueue(&q,2); 107 printf("Queue length: %d\n",q.count); 108 //Add more test codes 109 110 return 0; 111 }
posted on 2012-06-17 16:33 AlanLau2011 阅读(287) 评论(0) 收藏 举报
浙公网安备 33010602011771号