一、理解和感悟
1、用数组模拟队列,比用数组模拟栈要麻烦一点,因为栈是同一边进同一边出,而队列是尾巴进,脑袋出。
2、声明hh
,tt
时,就看出了算法模板的匠心独到,他把hh=0
,tt=-1
,这么赋值,为以后判断队列是不是为空就创造了条件,if(hh<=tt)
就是不空,反之if(hh>tt)
就是空了。
举个栗子
先加入一个元素a
,那么需要++tt
,就是tt==0
,然后要求a
出队,就是hh++
,这时,hh=1
,现在队列为空,hh>tt
。
3、因为数组的特点,在数组后面增加元素很方便,在头部增加元素很麻烦,所以设计了hh
在左,tt
在右的策略,出队hh++
,入队tt++
4、使用数组模拟队列的另一个好处,就是可以遍历队列中的每一个数字,这和用数组模拟栈是一样的,这也是\(STL\)比不了的。
二、完整代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
// hh 表示队头,tt表示队尾
int q[N], hh = 0, tt = -1;
// 向队尾插入一个数
void push(int x) {
q[++tt] = x;
}
// 从队头弹出一个数
void pop() {
hh++;
}
// 队头的值
int query() {
return q[hh];
}
// 判断队列是否为空
bool empty() {
return hh > tt;
}
int main() {
//优化输入
ios::sync_with_stdio(false);
int n;
cin >> n;
while (n--) {
string cmd;
cin >> cmd;
if (cmd == "push") {
int x;
cin >> x;
push(x);
} else if (cmd == "empty") {
bool res = empty();
if (res)cout << "YES" << endl;
else cout << "NO" << endl;
} else if (cmd == "query") {
int x = query();
cout << x << endl;
} else if (cmd == "pop") pop();
}
return 0;
}