用C语言写一个带注释的循环队列
时间: 2024-06-02 10:14:05 浏览: 16
/**
* 循环队列
*/
#include <stdio.h>
#include <stdlib.h>
#define QUEUE_SIZE 5 // 队列长度为5
typedef struct {
int *data; // 存放数据的数组
int front; // 队列头
int rear; // 队列尾
} Queue;
Queue *initQueue(); // 初始化队列
void enqueue(Queue *queue, int value); // 入队
int dequeue(Queue *queue); // 出队
void printQueue(Queue *queue); // 输出队列
int main() {
Queue *queue = initQueue(); // 初始化队列
enqueue(queue, 1); // 入队 1
enqueue(queue, 2); // 入队 2
enqueue(queue, 3); // 入队 3
printQueue(queue); // 输出队列
dequeue(queue); // 出队
dequeue(queue); // 出队
enqueue(queue, 4); // 入队 4
enqueue(queue, 5); // 入队 5
printQueue(queue); // 输出队列
dequeue(queue); // 出队
enqueue(queue, 6); // 入队 6
printQueue(queue); // 输出队列
return 0;
}
/**
* 初始化队列
*/
Queue *initQueue() {
Queue *queue = (Queue *)malloc(sizeof(Queue)); // 分配内存空间
queue->data = (int *)malloc(sizeof(int) * QUEUE_SIZE); // 分配内存空间
queue->front = 0; // 队列头指针初始化为0
queue->rear = 0; // 队列尾指针初始化为0
return queue; // 返回队列指针
}
/**
* 入队
*/
void enqueue(Queue *queue, int value) {
if ((queue->rear + 1) % QUEUE_SIZE == queue->front) { // 队列已满
printf("Queue is full.\n");
return;
}
queue->data[queue->rear] = value; // 数据入队
queue->rear = (queue->rear + 1) % QUEUE_SIZE; // 队列尾指针向后移一位
}
/**
* 出队
*/
int dequeue(Queue *queue) {
if (queue->front == queue->rear) { // 队列为空
printf("Queue is empty.\n");
return -1;
}
int value = queue->data[queue->front]; // 取出队头数据
queue->front = (queue->front + 1) % QUEUE_SIZE; // 队列头指针向后移一位
return value;
}
/**
* 输出队列
*/
void printQueue(Queue *queue) {
if (queue->front == queue->rear) { // 队列为空
printf("Queue is empty.\n");
return;
}
printf("Queue: ");
int i = queue->front;
while (i != queue->rear) { // 遍历队列
printf("%d ", queue->data[i]);
i = (i + 1) % QUEUE_SIZE; // 指针向后移一位
}
printf("\n");
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)