题目地址:
https://www.acwing.com/problem/content/831/
实现一个队列,队列初始为空,支持四种操作:
(1) “push x” – 向队尾插入一个数
x
x
x;
(2) “pop” – 从队头弹出一个数;
(3) “empty” – 判断队列是否为空;
(4) “query” – 查询队头元素。
现在要对队列进行
M
M
M个操作,其中的每个操作
3
3
3和操作
4
4
4都要输出相应的结果。
输入格式:
第一行包含整数
M
M
M,表示操作次数。接下来
M
M
M行,每行包含一个操作命令,操作命令为”push x”,”pop”,”empty”,”query”中的一种。
输出格式:
对于每个”empty”和”query”操作都要输出一个查询结果,每个结果占一行。其中,”empty”操作的查询结果为“YES”或“NO”,”query”操作的查询结果为一个整数,表示队头元素的值。
数据范围:
1
≤
M
≤
100000
1\le M\le 100000
1≤M≤100000
1
≤
x
≤
1
0
9
1\le x\le 10^9
1≤x≤109
用数组模拟队列。代码如下:
#include <iostream>
using namespace std;
const int N = 100010;
int q[N];
int hh, tt;
void push(int x) {
q[tt++] = x;
}
void pop() {
hh++;
}
bool empty() {
return hh == tt;
}
int query() {
return q[hh];
}
int main() {
int n;
cin >> n;
while (n--) {
string op;
int x;
cin >> op;
if (op == "push") {
cin >> x;
push(x);
} else if (op == "empty")
cout << (empty() ? "YES" : "NO") << endl;
else if (op == "query")
cout << query() << endl;
else if (op == "pop") pop();
}
return 0;
}
所有操作时间复杂度 O ( 1 ) O(1) O(1),空间取决于插入次数。