题解 | #【模板】循环队列#想抱抱他,又怕他生气
【模板】循环队列
https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int* data; // 动态分配的数组 int front; int rear; int capacity; // 队列的最大容量 }; typedef struct node* queue; void push(queue ptrs, int item) { if ((ptrs->rear + 1) % ptrs->capacity == ptrs->front) { printf("full\n"); // 队列已满,无法入队 return; } ptrs->rear = (ptrs->rear + 1) % ptrs->capacity; ptrs->data[ptrs->rear] = item; } int pop(queue ptrs) { if (ptrs->front == ptrs->rear) { printf("empty\n"); // 队列为空,无法出队 return -1; } ptrs->front = (ptrs->front + 1) % ptrs->capacity; return ptrs->data[ptrs->front]; } void front(queue ptrs) { if (ptrs->front == ptrs->rear) { printf("empty\n"); // 队列为空,无法获取头元素 return; } printf("%d\n", ptrs->data[(ptrs->front + 1) % ptrs->capacity]); } int main() { queue ptrs = (queue)malloc(sizeof(struct node)); int n, q; scanf("%d %d", &n, &q); ptrs->capacity = n + 1; // 额外预留一个空间,因为循环队列中一个位置不存储数据 ptrs->data = (int*)malloc(ptrs->capacity * sizeof(int)); ptrs->front = 0; ptrs->rear = 0; char operation[10]; int value; while (q--) { scanf("%s", operation); if (strcmp(operation, "push") == 0) { scanf("%d", &value); push(ptrs, value); } else if (strcmp(operation, "pop") == 0) { int result = pop(ptrs); if (result != -1) { printf("%d\n", result); } } else if (strcmp(operation, "front") == 0) { front(ptrs); } } free(ptrs->data); free(ptrs); return 0; }