题目1512:用两个栈实现队列

来源:互联网 发布:centos phomyadmin 编辑:程序博客网 时间:2024/05/03 00:41

时间限制:1 秒

内存限制:128 兆



题目描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。

输入:

每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。

输出:

对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

样例输入:
3PUSH 10POPPOP
样例输出:
10-1
题目分析:使用两个栈模拟队列, 队列是FIFO,栈是FILO, 此题方法巧妙,时间复杂度为O(n), 代码已AC。
#include <iostream>#include <cstdio>#include <queue>#include <stack>#include <cstring>using namespace std;stack<int> st1;stack<int> st2;char str[6];int main(void){int n, val;scanf("%d", &n);for (int i = 0; i < n; ++i){scanf("%s", str);if (str[1] == 'U'){scanf("%d", &val);st2.push(val);}else{if (st1.empty()){while(!st2.empty()){st1.push(st2.top());st2.pop();}}if (st1.empty())printf("-1\n");else{printf("%d\n", st1.top());st1.pop();}}}return 0;}


0 0
原创粉丝点击