题解 | #【模板】循环队列#
【模板】循环队列
https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Queuelink {
int front;
int rear;
int maxsize;
int* data;
} QueueLink;
void QueueInit(QueueLink* Q, int max) {
Q->data = (int*)malloc(sizeof(int) * (max+1));
Q->front = 0;
Q->rear = 0;
Q->maxsize = max+1;
}
void Queuepush(QueueLink* Q, int x) {
if ((Q->rear + 1) % Q->maxsize == Q->front) {
printf("full\n");
return;
}
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % Q->maxsize;
}
void Queuefront(QueueLink* Q) {
if (Q->front == Q->rear) {
printf("empty\n");
return;
}
printf("%d\n", Q->data[Q->front]);
}
void Queuepop(QueueLink* Q) {
if (Q->front == Q->rear) {
printf("empty\n");
return;
}
printf("%d\n", Q->data[Q->front]);
Q->front = (Q->front + 1) % Q->maxsize;
}
int main() {
int a, q, n;
char str[6];
QueueLink Q;
scanf("%d %d", &n, &q);
QueueInit(&Q, n);
for (int i = 0; i < q; i++) {
scanf("%s %d", str, &a);
if (strcmp(str, "pop") == 0) {
Queuepop(&Q);
} else if (strcmp(str, "front") == 0) {
Queuefront(&Q);
} else if (strcmp(str, "push") == 0) {
Queuepush(&Q, a);
}
}
return 0;
}

查看1道真题和解析