1.使用了数组来表达循环
cpp
typedef struct {
int k;//数据个数
int *a;//数组
int rear;//尾
int front;//头
} MyCircularQueue;
2.循环队列是否为空
cpp
bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
return obj->rear == obj->front;
}
3.循环队列是否已满。
cpp
bool myCircularQueueIsFull(MyCircularQueue* obj) {
return (obj->rear+1)%(obj->k+1) == obj->front;
}
4.初始化
cpp
MyCircularQueue* myCircularQueueCreate(int k) {
MyCircularQueue*obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
obj->a = (int*)malloc(sizeof(int)*(k+1));
obj->k = k;
obj->rear = obj->front = 0;
return obj;
}
5.向循环队列插入一个元素。如果成功插入则返回真
cpp
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
if(myCircularQueueIsFull(obj))
return false;
obj->a[obj->rear] = value;
obj->rear++;
obj->rear %= (obj->k+1);
return true;
}
6.从队首获取元素。如果队列为空,返回 -1
cpp
int myCircularQueueFront(MyCircularQueue* obj) {
if(myCircularQueueIsEmpty(obj))
return -1;
return obj->a[obj->front];
}
7.获取队尾元素。如果队列为空,返回 -1
cpp
int myCircularQueueRear(MyCircularQueue* obj) {
if(myCircularQueueIsEmpty(obj))
return -1;
return obj->a[(obj->rear+obj->k)%(obj->k+1)];
}
8.销毁空间
cpp
void myCircularQueueFree(MyCircularQueue* obj) {
free(obj->a);
free(obj);
}