以下是使用 C 语言实现循环队列,并通过增设 tag 变量区分队列是否为空或满的代码示例:

#include <stdio.h>

#define SIZE 5

typedef struct {
    int items[SIZE];
    int front;
    int rear;
    int tag;
} Queue;

void init(Queue *q) {
    q->front = -1;
    q->rear = -1;
    q->tag = 0;
}

int isEmpty(Queue *q) {
    if (q->tag == 0) {
        return 1;
    } else {
        return 0;
    }
}

int isFull(Queue *q) {
    if (q->tag == 1) {
        return 1;
    } else {
        return 0;
    }
}

void enqueue(Queue *q, int value) {
    if (isFull(q)) {
        printf("Queue is full.\n");
    } else {
        if (q->rear == SIZE - 1) {
            q->rear = 0;
        } else {
            q->rear++;
        }
        q->items[q->rear] = value;
        q->tag = 1;
        if (q->front == -1) {
            q->front = 0;
        }
    }
}

int dequeue(Queue *q) {
    int value;
    if (isEmpty(q)) {
        printf("Queue is empty.\n");
        return -1;
    } else {
        value = q->items[q->front];
        if (q->front == q->rear) {
            q->front = -1;
            q->rear = -1;
            q->tag = 0;
        } else if (q->front == SIZE - 1) {
            q->front = 0;
        } else {
            q->front++;
        }
        return value;
    }
}

int main() {
    Queue q;
    init(&q);

    enqueue(&q, 1);
    enqueue(&q, 2);
    enqueue(&q, 3);
    enqueue(&q, 4);
    enqueue(&q, 5);

    printf("Is queue empty? %s\n", isEmpty(&q) ? "Yes" : "No");
    printf("Is queue full? %s\n", isFull(&q) ? "Yes" : "No");

    dequeue(&q);
    dequeue(&q);
    dequeue(&q);

    printf("Is queue empty? %s\n", isEmpty(&q) ? "Yes" : "No");
    printf("Is queue full? %s\n", isFull(&q) ? "Yes" : "No");

    return 0;
}

这是一个使用循环数组实现的循环队列,并通过增设tag变量区分循环队列是否为空或满。在初始化时,tag被设置为0表示队列为空。当队列中有元素入队时,tag被设置为1表示队列不为空。当队列中的元素全部出队时,tag被重新设置为0表示队列为空。当rear与front相等且tag为1时,表示队列已满。enqueue函数和dequeue函数分别用于入队和出队操作,并根据队列的状态进行相应的操作。在主函数中,我们进行了一些入队和出队操作,并通过isEmpty函数和isFull函数来判断队列是否为空或满。

C语言实现循环队列:使用tag变量区分空与满

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

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