题解 | #AB8 【模板】循环队列#
【模板】循环队列
http://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
C语言版本
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct tQueue {
int *data, size, front, rear;
} Queue;
void initQueue(Queue *pQ, int n) {
pQ->data = (int*)malloc(sizeof(int)*(n+1));
pQ->size = n+1;
pQ->front = 0;
pQ->rear = 0;
}
bool isEmpty(Queue *pQ) {
return (pQ->front == pQ->rear);
}
bool isFull(Queue *pQ) {
return ((1+pQ->rear)%(pQ->size) == pQ->front);
}
bool enQueue(Queue *pQ, int *x) {
if (isFull(pQ)) {
return false;
} else {
pQ->data[pQ->rear] = *x;
pQ->rear = (1+pQ->rear)%(pQ->size);
return true;
}
}
bool deQueue(Queue *pQ, int *x) {
if(isEmpty(pQ)) {
return false; //空队
} else {
*x = pQ->data[pQ->front];
pQ->front = (1+pQ->front)%(pQ->size);
return true;
}
}
bool getFront(Queue *pQ, int *x) {
if (isEmpty(pQ)) {
return false;
} else {
*x = pQ->data[pQ->front];
return true;
}
}
int main() {
int n, q, x;
char temp[10];
bool ret;
scanf("%d%d", &n, &q);
Queue Q;
initQueue(&Q, n);
for (int i = 0; i < q; i++) {
scanf("%s", temp);
if (strcmp(temp, "push") == 0) {
scanf("%d", &x);
ret = enQueue(&Q, &x);
if (!ret) {
printf("full\n");
}
} else if (strcmp(temp, "front") == 0) {
ret = getFront(&Q, &x);
if (!ret) {
printf("empty\n");
} else {
printf("%d\n", x);
}
} else if (strcmp(temp, "pop") == 0) {
ret = deQueue(&Q, &x);
if (!ret) {
printf("empty\n");
} else {
printf("%d\n", x);
}
}
}
return 0;
}