题解 | #【模板】队列#
【模板】队列
https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549?tpId=308&tqId=2110348&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308
#include<stdio.h> #include<stdlib.h> #include<string.h> #define true 1 #define false 0 #define Max_Size 100000 typedef int _bool; typedef struct{ int data[Max_Size]; int front; int rear; }*Queue; _bool Init_Queue(Queue* Q);//初始化队列 _bool Push(Queue* Q,int x);//将加入队列Q的队尾 _bool Pop(Queue* Q);//输出队首并让队首出队 void Front(Queue* Q);//输出队首,队首不出队 int main(void){ Queue Q; Init_Queue(&Q); int n = 0;//操作次数 char str[6];//操作名 int x = 0;//入队元素 scanf("%d",&n); while(n > 0){ n--; scanf("%s",str); if(strcmp(str,"push") == 0){ scanf("%d",&x); Push(&Q,x); } if(strcmp(str,"pop") == 0) { Pop(&Q); } if(strcmp(str,"front") == 0){ Front(&Q); } //将存操作名的数组初始为空,不然影响下次操作名比较 for(int i = 0; i < 5;i++) { str[i] = ' '; } //n--; } return 0; } _bool Init_Queue(Queue* Q){ *Q = (Queue)malloc(sizeof(int)*(Max_Size + 2)); (*Q)->front = 0; (*Q)->rear = 0; return true; } _bool Push(Queue* Q,int x){ if((*Q)->rear < Max_Size - 1){ (*Q)->data[(*Q)->rear] = x; //printf("%d\n",((*Q)->data[(*Q)->rear])); (*Q)->rear++; return true; } else{ printf("error\n"); return false; } } _bool Pop(Queue* Q){ if((*Q)->front == (*Q)->rear){//空 printf("error\n"); return false; } printf("%d\n",((*Q)->data[(*Q)->front])); (*Q)->front++; return true; } void Front(Queue* Q){ if((*Q)->front == (*Q)->rear){ //空 printf("error\n"); return; } printf("%d\n",(*Q)->data[(*Q)->front]); }