队列的循环数组实现

这里初始化的队列的front一直指向队头,rear一直指向队尾。

  1 #include "pch.h"
  2 #include <iostream>
  3 #include <stdlib.h>
  4 using namespace std;
  5 
  6 #define MinQueueSize 5    //限定队列的最小容量
  7 
  8 struct QueueRecord        //记录队列的相关信息
  9 {
 10     int cap;    
 11     int front;
 12     int rear;
 13     int size;//目前队列大小
 14     int* array;
 15 };
 16 typedef struct QueueRecord* queue;
 17 
 18 //创建一个空队列,自定义容量
 19 queue create_empty_queue(int capacity)
 20 {
 21     if (capacity < MinQueueSize)
 22         cout << "请指定更大的容量" << endl;
 23     else
 24     {
 25         queue Q = (queue)malloc(sizeof(struct QueueRecord));
 26         Q->cap = capacity;
 27         Q->array = (int*)malloc(sizeof(int)*capacity);
 28         Q->size = 0;
 29         Q->front = 1;
 30         Q->rear = 0;//初始化front和rear,rear位于front后面
 31         return Q;
 32     }
 33     
 34 }
 35 //检测队列是否为空
 36 bool isempty(queue Q)
 37 {
 38     return Q->size == 0;
 39 }
 40 //检测队列是否为满
 41 bool isfull(queue Q)
 42 {
 43     return Q->size == Q->cap;
 44 }
 45 //释放队列
 46 void dispose_queue(queue Q)
 47 {
 48     if (Q != NULL)
 49     {
 50         free(Q->array);
 51         free(Q);
 52     }
 53 }
 54 //返回队列长度
 55 int length_queue(queue Q)
 56 {
 57     return Q->size;
 58 }
 59 //判断front或rear是否到达了数组的末端,若是则绕回开头
 60 int Succ(int &value, queue Q)
 61 {
 62     if (++value == Q->cap)
 63         value = 0;
 64     return value;
 65 }
 66 //入队
 67 void Enqueue(queue Q,int x)
 68 {
 69     if (isfull(Q))
 70         cout << "队列已满" << endl;
 71     else
 72     {
 73         Q->size++;
 74         Q->rear = Succ(Q->rear, Q);
 75         Q->array[Q->rear] = x;
 76     }
 77 }
 78 //出队
 79 void Dequeue(queue Q)
 80 {
 81     if (isempty(Q))
 82         cout << "队列已空" << endl;
 83     else
 84     {
 85         Q->size--;
 86         Q->front = Succ(Q->front, Q);
 87     }
 88 }
 89 //返回队头的值
 90 int value_front(queue Q)
 91 {
 92     if (isempty(Q))
 93         cout << "队列为空" << endl;
 94     else
 95         return Q->array[Q->front];
 96 }
 97 int value_rear(queue Q)
 98 {
 99     if (isempty(Q))
100         cout << "队列为空" << endl;
101     else
102         return Q->array[Q->rear];
103 }
104 int main()
105 {
106     queue Q=create_empty_queue(5);
107     if (isempty)
108         cout << "这是一个空队列" << endl;
109     Dequeue(Q);
110     for (int i = 0; i < 6; i++)
111         Enqueue(Q, i);
112     cout << value_front(Q) << " " << value_rear(Q) << endl;
113     system("pause");
114     return 0;
115 
116 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/cs0915/p/12143393.html