题目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
推荐指数:※※
来源: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值