2016级数据结构第四次上机A

时间:2021-05-01 09:50:04

题目描述

每天中午食堂都会有很多人,为了维持秩序,食堂的负责人决定钦点mdd来负责排队。因为食堂空间有限,每条队伍只能容纳20个人,人满的话是进不了队伍的。

输入

一组输入数据

对于每组数据,一开始队伍为空

每组数据都有多行命令,分别是offer x,poll,peek,分别表示让编号为x的同学进入队伍,让队首的同学离开,查询队首的编号。

输出

如果命令是peek,输出队首同学的编号。在操作过程中,如果操作不合法,则输出“fool!”

输入样例

offer 1
peek
poll
peek

输出样例

1
fool!

算法分析

考察基本的队列操作,我用循环队列来实现。循环队列要注意开一个大小为maxSize的数组,只能放maxSize-1人,所以这里maxSize是21。

参考代码

 1 #include <iostream>
2 #include <string>
3 #define maxSize 21
4 using namespace std;
5 struct circqueue
6 {
7 int student[maxSize];
8 int front,rear;
9 }q;
10 void Initqueue(circqueue &q)
11 {
12 q.front=q.rear=0;
13 }
14 int Enqueue(circqueue &q,int x)
15 {
16 if((q.rear+1)%maxSize==q.front) return 0;
17 q.student[q.rear]=x;
18 q.rear=(q.rear+1)%maxSize;
19 return 1;
20 }
21 int Dequeue(circqueue &q,int &x)
22 {
23 if(q.front==q.rear) return 0;
24 x=q.student[q.front];
25 q.front=(q.front+1)%maxSize;
26 return 1;
27 }
28 int GetFront(circqueue &q,int &x)
29 {
30 if(q.front==q.rear) return 0;
31 x=q.student[q.front];
32 return 1;
33 }
34 int main()
35 {
36 string op;
37 Initqueue(q);
38 while(cin>>op){
39 if(op=="offer"){
40 int x;
41 cin>>x;
42 if(Enqueue(q,x)==0) cout<<"fool!"<<endl;
43 }
44 else if(op=="poll"){
45 int y;
46 int flag=Dequeue(q,y);
47 if(flag==0) cout<<"fool!"<<endl;
48 }
49 else if(op=="peek"){
50 int z;
51 if(GetFront(q,z)==0){
52 cout<<"fool!"<<endl;
53 }
54 else{
55 cout<<z<<endl;
56 }
57 }
58 }
59 }