- 题目描述:
-
用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
- 输入:
-
每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。
- 输出:
-
对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。
- 样例输入:
-
3 PUSH 10 POP POP
- 样例输出:
-
10 -1
主要思路:建立两个栈S1,S2,当执行PUSH操作时将数据压到S1中;当执行POP操作时分两种情况:1、如果S2不为空,则从S2中弹出一个数并输出;2、如果S2为空S1不为空则将S1中的数据全部导入S2中,如果两个都为空则表示队列中没有数字,输出-1。
C++代码:
#include<stdio.h> #include<string.h> #include<stack> using namespace std; stack<int> S1,S2; int main(){ int n; while(scanf("%d",&n)!=EOF){ char cmd[30]; for(int i=0;i<n;i++){ scanf("%s",cmd); if(cmd[1]=='U'){ int res=0; scanf("%d",&res); S1.push(res); } else{ if(S2.empty()==false){ int t=S2.top();S2.pop(); printf("%d\n",t); } else{ if(S1.empty()) printf("-1\n"); else{ while(S1.empty()==false){ S2.push(S1.top()); S1.pop(); } printf("%d\n",S2.top()); S2.pop(); } } } } } return 0; }