C++ 队列模板题:模拟实现队列操作
C++ 队列模板题:模拟实现队列操作
题目描述
模拟实现一个队列,有 n 个操作,操作包括:
'Push' x:在当前队列末尾入队一个元素x;'Pop':输出当前队头元素,并令队头出队。
输入格式
从标准输入读入数据。
第一行输入一个正整数 n(n <= 10^6)。
接下来每行输入一个操作,操作中的元素值均为不大于 10^6 的正整数。
输出格式
输出到标准输出。
对于每个 'Pop' 操作,输出一行。
注意:如果 'Pop' 时队列为空,对该操作输出 -1 并不执行出队操作。
样例 #1
样例输入 #1
6
'Push' 3
'Push' 4
'Pop'
'Push' 5
'Pop'
'Pop'
样例输出 #1
3
4
5
C++ 代码实现
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
queue<int> q;
for (int i = 0; i < n; i++) {
string op;
cin >> op;
if (op == "Push") {
int x;
cin >> x;
q.push(x);
} else if (op == "Pop") {
if (!q.empty()) {
cout << q.front() << endl;
q.pop();
} else {
cout << -1 << endl;
}
}
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/qvU1 著作权归作者所有。请勿转载和采集!