http://ac.jobdu.com/problem.php?pid=1512
题目1512:用两个栈实现队列
-
题目描述:
-
用两个栈来实现一个队列,完成队列的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
<span style="font-size:18px;">#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
stack<int> stack1;
stack<int> stack2;
void appendTail(int x) {
stack1.push(x);
}
void deleteHead() {
if (!stack2.empty()) {
printf("%d\n", stack2.top());
stack2.pop();
}
else if (!stack1.empty()){
while(!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
printf("%d\n", stack2.top());
stack2.pop();
}
else
printf("-1\n");
}
int main() {
int n;
char op[10];
while(scanf("%d", &n) != EOF) {
while (!stack1.empty())
stack1.pop();
while (!stack1.empty())
stack2.pop();
for(int j = 0; j < n; j ++){
scanf("%s", op);
if (op[1] == 'U') {//PUSH
int num;
scanf("%d", &num);
appendTail(num);
}
else //POP
deleteHead();
}
}
return 0;
}
/**************************************************************
Problem: 1512
Language: C++
Result: Accepted
Time:70 ms
Memory:1184 kb
****************************************************************/</span><span style="font-size: 18px;">
</span>
tips:入队时,直接压入栈1
出队时,若栈2有数字,直接弹栈;没有,则从栈1输出到栈2.
无需每次都把栈里的数字都放到一个栈中,只有当栈2没有数字时,才考虑从栈1导入。否则,若数据量过大,时间消耗太多!