C语言实现环形队列:代码示例及解析

以下是一个基于数组的环形队列的C语言实现示例:

#include <stdio.h>
#include <stdlib.h>

#define MAX_QUEUE_SIZE 5 // 队列最大容量

typedef struct {
    int front; // 队头指针
    int rear; // 队尾指针
    int data[MAX_QUEUE_SIZE]; // 队列数据
} Queue;

// 初始化队列
void initQueue(Queue *q) {
    q->front = q->rear = 0;
}

// 入队操作
void enqueue(Queue *q, int value) {
    if ((q->rear + 1) % MAX_QUEUE_SIZE == q->front) {
        printf("Queue is full!\n");
        return;
    }
    q->data[q->rear] = value;
    q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}

// 出队操作
int dequeue(Queue *q) {
    if (q->front == q->rear) {
        printf("Queue is empty!\n");
        return -1;
    }
    int value = q->data[q->front];
    q->front = (q->front + 1) % MAX_QUEUE_SIZE;
    return value;
}

// 打印队列
void printQueue(Queue *q) {
    if (q->front == q->rear) {
        printf("Queue is empty!\n");
        return;
    }
    printf("Queue: ");
    int i = q->front;
    while (i != q->rear) {
        printf("%d ", q->data[i]);
        i = (i + 1) % MAX_QUEUE_SIZE;
    }
    printf("\n");
}

int main() {
    Queue q;
    initQueue(&q);
    enqueue(&q, 1);
    enqueue(&q, 2);
    enqueue(&q, 3);
    enqueue(&q, 4);
    enqueue(&q, 5);
    printQueue(&q); // 队列已满,输出:Queue is full!
    dequeue(&q);
    dequeue(&q);
    enqueue(&q, 6);
    enqueue(&q, 7);
    printQueue(&q); // 队列:3 4 5 6 7
    return 0;
}

代码中使用了一个数组来存储队列元素,队列的大小为 MAX_QUEUE_SIZE,需要注意的是队列的实际大小比数组容量小1,这是因为在队列满时需要留一个空位来区分队列满和队列空。frontrear 分别表示队列的头指针和尾指针,初始时两者均为0。当执行入队操作时,如果队列已满,则输出错误提示信息,否则将元素存入数组,并将尾指针后移一位。当执行出队操作时,如果队列为空,则输出错误提示信息,否则将头指针后移一位,并返回队头元素。打印队列时,从头指针开始遍历到尾指针前一位,输出每个元素。

环形队列的优点:

  • 可以有效地利用数组空间,避免数组空间浪费。
  • 在队列满或空时,可以进行循环操作,提高效率。

环形队列的应用场景:

  • 操作系统中的缓冲区管理
  • 网络数据包处理
  • 打印机任务队列
  • 多线程通信
C语言实现环形队列:代码示例及解析

原文地址: https://www.cveoy.top/t/topic/nVoQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录