请用C语言代码编写程序实现环形队列,能够进行进队及出队操作。第一行包含一个整数 q\ (q\le 31000)q (q≤31000),表示操作的个数,接下来 qq 行,每行格式如下: enqueue x:表示让整数 xx 进队(0\le x\lt 2000≤x<200); dequeue:表示出队。
时间: 2024-02-22 19:59:11 浏览: 38
好的,我来为您编写环形队列的代码,如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000
typedef struct {
int data[MAX_SIZE];
int front, rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isEmpty(Queue *q) {
return q->front == q->rear;
}
int isFull(Queue *q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
void enqueue(Queue *q, int x) {
if (isFull(q)) {
printf("Error: Queue is full!\n");
exit(-1);
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAX_SIZE;
}
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Error: Queue is empty!\n");
exit(-1);
}
int x = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return x;
}
int main() {
Queue q;
initQueue(&q);
int qNum;
scanf("%d", &qNum);
while (qNum--) {
char op[10];
scanf("%s", op);
if (op[0] == 'e') {
int x;
scanf("%d", &x);
enqueue(&q, x);
} else {
printf("%d\n", dequeue(&q));
}
}
return 0;
}
```
代码中,我们使用结构体 `Queue` 来表示队列,其中 `data` 数组用于存储队列元素,`front` 和 `rear` 分别表示队头和队尾的下标。初始化函数 `initQueue` 将队头和队尾都初始化为 0。`isEmpty` 和 `isFull` 函数分别用于判断队列是否为空和是否已满。`enqueue` 函数用于将元素插入队尾,出队函数 `dequeue` 将队头元素出队,并返回它的值。
在 `main` 函数中,我们首先初始化队列,然后读入操作的个数 `qNum`,接着循环读入每个操作字符串,如果是 `enqueue`,则读入一个整数并将其插入队尾,否则执行出队操作并打印出队元素的值。