-
题目描述:
-
用两个栈来实现一个队列,完成队列的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
推荐指数:※※
来源:http://ac.jobdu.com/problem.php?pid=1512
使用两个栈模拟拟出队列的先进先出的规制。当把一个栈的内容导入到里一个栈当中是,其实最先压栈的元素,就到了栈顶,符合队列性质。
#include<iostream> #include<stack> #include<string.h> #include<stdio.h> using namespace std; int main() { int n,i; scanf("%d",&n); stack<int> st_o; stack<int> st_u; for(i=0;i<n;i++){ char s[5]; scanf("%s",s); if(s[1]=='U'){ int x; scanf("%d",&x); st_u.push(x); } else if(s[1]=='O'){ if(!st_o.empty()){ printf("%d\n",st_o.top()); st_o.pop(); } else if(!st_u.empty()){ while(!st_u.empty()){ st_o.push(st_u.top()); st_u.pop(); } printf("%d\n",st_o.top()); st_o.pop(); } else printf("-1\n"); } else { printf("Invalid\n"); break; } } return 0; }
下面是一个未经优化,有一个case超时:
#include<iostream> #include<stack> #include<string.h> #include<stdio.h> using namespace std; int main() { int n,i; scanf("%d",&n); stack<int> st_o; stack<int> st_u; for(i=0;i<n;i++){ char s[5]; scanf("%s",s); if(s[1]=='U'){ int x; scanf("%d",&x); while(!st_o.empty()){ st_u.push(st_o.top()); st_o.pop(); } st_u.push(x); } else if(s[1]=='O'){ while(!st_u.empty()){ st_o.push(st_u.top()); st_u.pop(); } if(!st_o.empty()){ printf("%d\n",st_o.top()); st_o.pop(); } else printf("-1\n"); } else { printf("Invalid\n"); break; } } return 0; }