数据结构模板复习2:队列
引入
队列(queue)是一种具有先进入队列的元素一定先出队列性质的表。由于该性质,队列通常也被称为先进先出(first in first out)表,简称 FIFO 表。
注意
栈属于先进后出的数据结构,队列属于先进先出的数据结构
题目大意
实现一个队列(queue),支持如下操作:
- push(x):向队列中加入一个数 x。
- pop():将队首弹出。如果此时队列为空,则不进行弹出操作,并输出 ERR_CANNOT_POP。
- query():输出队首元素。如果此时队列为空,则输出 ERR_CANNOT_QUERY。
- size():输出此时队列内元素个数。
手写队列
通常用一个数组模拟一个队列,用两个变量标记队列的首尾。
int q[SIZE], ql = 1, qr;
队列操作对应的代码如下:
· 插入元素:q[++qr] = x;
· 删除元素:ql++;
· 访问队首:q[ql]
· 访问队尾:q[qr]
· 清空队列:ql = 1; qr = 0;
AC code
#include <bits/stdc++.h>
#define iosFast ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define File(x) freopen(x".in", "r", stdin); freopen(x".out", stdout)
#define loop(i, x, y) for (int i = x; i <= y; i ++)
#define push_back emplace_back
#define int long long
#define endl "\n"
using namespace std;
namespace LYX {
const int N = 1e6 + 100;
int q[N], ql = 1, qr = 0;
void solve() {
int n;
cin >> n;
loop(i, 1, n) {
int op;
cin >> op;
if (op == 1) {
int x;
cin >> x;
q[++qr] = x;
} else if (op == 2) {
if (ql <= qr) ++ql;
else cout << "ERR_CANNOT_POP" << endl;
}
else if (op == 3) {
if (ql <= qr) cout << q[ql];
else cout << "ERR_CANNOT_QUERY";
cout << endl;
}
else cout << qr - ql + 1 << endl;
}
}
signed main() {
int T = 1; //cin >> T;
while (T--) solve();
return 0;
}
}
signed main() {
iosFast;
return LYX::main();
}
STL 中的队列
C++ STL 中的队列 C++ 在 STL 中提供了一个容器 std::queue,使用前需要先引入 <queue> 头文件。
STL 中的 queue 容器提供了一众成员函数以供调用。其中较为常用的有:
元素访问
q.front()返回队首元素q.back()返回队尾元素 修改q.push()在队尾插入元素q.pop()弹出队首元素 容量q.empty()队列是否为空q.size()返回队列中元素的数量
和栈一样,你也很快就能写出代码
#include <bits/stdc++.h>
#define iosFast ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define File(x) freopen(x".in", "r", stdin); freopen(x".out", stdout)
#define loop(i, x, y) for (int i = x; i <= y; i ++)
#define push_back emplace_back
#define int long long
#define endl "\n"
using namespace std;
namespace LYX {
queue<int> q;
void solve() {
int n;
cin >> n;
loop(i, 1, n) {
int op;
cin >> op;
if (op == 1) {
int x;
cin >> x;
q.push(x);
} else if (op == 2) {
if (!q.empty()) q.pop();
else cout << "ERR_CANNOT_POP" << endl;
}
else if (op == 3) {
if (!q.empty()) cout << q.front();
else cout << "ERR_CANNOT_QUERY";
cout << endl;
}
else cout << q.size() << endl;
}
}
signed main() {
int T = 1; //cin >> T;
while (T--) solve();
return 0;
}
}
signed main() {
iosFast;
return LYX::main();
}