循环队列

C语言实现

#include <stdio.h>
#define MAX_SIZE 10

typedef struct {
    int queue[MAX_SIZE];
    int front;
    int rear;
} CircularQueue;

void initializeQueue(CircularQueue *cq) {
    cq->front = -1;
    cq->rear = -1;
}

int isEmpty(CircularQueue *cq) {
    return cq->front == -1;
}

int isFull(CircularQueue *cq) {
    return (cq->rear + 1) % MAX_SIZE == cq->front;
}

void enqueue(CircularQueue *cq, int item) {
    if (isFull(cq)) {
        printf("Queue is full. Cannot enqueue.\n");
        return;
    }

    if (isEmpty(cq)) {
        cq->front = 0;
    }

    cq->rear = (cq->rear + 1) % MAX_SIZE;
    cq->queue[cq->rear] = item;
}

int dequeue(CircularQueue *cq) {
    if (isEmpty(cq)) {
        printf("Queue is empty. Cannot dequeue.\n");
        return -1;
    }

    int item = cq->queue[cq->front];

    if (cq->front == cq->rear) {
        cq->front = -1;
        cq->rear = -1;
    } else {
        cq->front = (cq->front + 1) % MAX_SIZE;
    }

    return item;
}

void display(CircularQueue *cq) {
    if (isEmpty(cq)) {
        printf("Queue is empty.\n");
        return;
    }

    int i = cq->front;
    do {
        printf("%d ", cq->queue[i]);
        i = (i + 1) % MAX_SIZE;
    } while (i != (cq->rear + 1) % MAX_SIZE);
    printf("\n");
}

int main() {
    CircularQueue cq;
    initializeQueue(&cq);

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

    printf("Queue elements: ");
    display(&cq);

    printf("Dequeue: %d\n", dequeue(&cq));
    printf("Dequeue: %d\n", dequeue(&cq));

    printf("Queue elements after dequeue: ");
    display(&cq);

    enqueue(&cq, 6);
    enqueue(&cq, 7);

    printf("Queue elements after enqueue: ");
    display(&cq);

    return 0;
}
posted @ 2023-08-12 21:38  __Helios  阅读(7)  评论(0编辑  收藏  举报