C++ 循环队列的实现
时间: 2023-10-29 14:06:28 浏览: 55
循环队列是一种基于数组实现的队列数据结构。它的特点是在队尾元素之后还有一部分空间可以利用,实现了循环复用的效果。以下是一种基本的循环队列的实现方式:
```c
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front; // 队头指针
int rear; // 队尾指针
} CircularQueue;
// 初始化循环队列
void initQueue(CircularQueue *queue) {
queue->front = queue->rear = 0;
}
// 判断循环队列是否为空
int isEmpty(CircularQueue *queue) {
return queue->front == queue->rear;
}
// 判断循环队列是否已满
int isFull(CircularQueue *queue) {
return (queue->rear + 1) % MAX_SIZE == queue->front;
}
// 入队操作
void enqueue(CircularQueue *queue, int value) {
if (isFull(queue)) {
printf("Queue is full, cannot enqueue.\n");
return;
}
queue->data[queue->rear] = value;
queue->rear = (queue->rear + 1) % MAX_SIZE; // 更新队尾指针
}
// 出队操作
int dequeue(CircularQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty, cannot dequeue.\n");
return -1;
}
int value = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE; // 更新队头指针
return value;
}
```
使用上述代码可以实现基本的循环队列,并提供入队和出队的操作。需要注意的是,在入队和出队操作时,需要对队尾指针和队头指针进行取模运算,以实现循环复用的效果。