用c语言编程实现循环队列的入队列,计算该队列长度,然后出队列
时间: 2024-04-21 22:15:07 浏览: 69
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int front, rear;
} Queue;
void enqueue(Queue *q, int value) {
if ((q->rear + 1) % MAX_SIZE == q->front) {
printf("Queue is full, cannot enqueue.\n");
return;
}
q->data[q->rear] = value;
q->rear = (q->rear + 1) % MAX_SIZE;
}
int dequeue(Queue *q) {
if (q->front == q->rear) {
printf("Queue is empty, cannot dequeue.\n");
return -1;
}
int value = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return value;
}
int queue_length(Queue *q) {
return (q->rear - q->front + MAX_SIZE) % MAX_SIZE;
}
int main() {
Queue q = { .front = 0, .rear = 0 };
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("Queue length: %d\n", queue_length(&q));
printf("Dequeue: %d\n", dequeue(&q));
printf("Dequeue: %d\n", dequeue(&q));
printf("Queue length: %d\n", queue_length(&q));
enqueue(&q, 4);
printf("Queue length: %d\n", queue_length(&q));
return 0;
}
阅读全文