题解 | #【模板】队列#
【模板】队列
https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549
#include <stdio.h>
#include <string.h>
#define N 1000000
typedef struct Queue {
int front;
int rear;
int data[N];
} Queue;
void QueueInit(Queue* q) {
q->front = 0;
q->rear = 0;
}
void QueuePush(Queue* q, int x) {
q->data[q->rear] = x;
q->rear = q->rear+1; // Ensure circular behavior
}
void QueuePop(Queue* q) {
if (q->front == q->rear) {
printf("error\n");
return;
}
printf("%d\n",q->data[q->front]);
q->front+=1;
}
void QueueFront(Queue* q) {
if (q->front == q->rear) {
printf("error\n");
return;
}
printf("%d\n", q->data[q->front]);
}
int main() {
Queue s;
char str[6];
int b, n;
QueueInit(&s);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s %d",str,&b);
if (strcmp(str, "push") == 0) {
QueuePush(&s, b);
} else if (strcmp(str, "pop") == 0) {
QueuePop(&s);
} else if (strcmp(str, "front") == 0) {
QueueFront(&s);
}
}
return 0;
}

