题解 | #【模板】循环队列#非链式存储方法
【模板】循环队列
https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
#include <stdio.h> #include <string.h> typedef struct { int data[10000]; int front, rear; } SqQueue; void initQueue(SqQueue* Q) { Q->front = Q->rear = 0; } int enQueue(SqQueue* Q, int x, int size) { if ((Q->rear + 1) % size == Q->front) { printf("full\n"); return 0; } Q->data[Q->rear] = x; Q->rear = (Q->rear + 1) % size; return 1; } int DeQueue(SqQueue* Q, int* x, int size) { if (Q->front == Q->rear) { printf("empty\n"); return 0; } *x = Q->data[Q->front]; Q->front = (Q->front + 1) % size; return 1; } int read(SqQueue* Q) { if (Q->front == Q->rear) { printf("empty\n"); return 0; } printf("%d\n", Q->data[Q->front]); return 1; } int main() { SqQueue Q; initQueue(&Q); int size; int n, i = 1; char s[1000]; int k; scanf("%d %d", &size, &n); while (i <= n) { scanf("%s %d", s, &k); if (strcmp(s, "push") == 0) { enQueue(&Q, k, size+1);//size必须加一,循环队列会浪费一个空间所以必须加一保证足够的储存空间 } if (strcmp(s, "pop") == 0) { if (DeQueue( &Q, &k, size+1)) { printf("%d\n", k); } } if (strcmp(s, "front") == 0) { read(&Q); } i++; } return 0; }