剑指Offer之用两个栈实现队列
来源:互联网 发布:世界各国软件行业排名 编辑:程序博客网 时间:2024/05/29 15:13
栈的性质是先进后出,队列是先进先出。但是我们可以使用两个栈来模拟队列的操作。比如一个序列a,b,c。我们可以将其压入stack1中,stack1中的值为从栈顶到栈底为c,b,a如果此时要出队列的话,可以将stack1中得元素全部压入stack2中,弹出stack2中的头部。即为a,如果要接着输出队列的话可以将stack2里的元素接着弹出,即为b,但是,如果此时想要插入一个元素d。这是如果想着把d直接压入stack2中的话显然是不对的了,要是下次再弹出元素的话直接弹出d,但是d是最后才入列的。这里有两种方法,一种是将stack2中得元素全部压入stack1中,此时再将d压入stack1中,弹出时再将stack1中得元素压入stack2中。但是这么折腾显然效率不高。我们回到要插入d的时候。此时stack1是空的,我们可以把d压入stack1中,但是如果要弹出d时应该这么操作。此时stack2不为空,就意味着有多少元素是在d之前的,那么弹出stack2中得元素,直到为空,然后将d转而压入到stack2中。
因此我们可以这么操作,每次想要压入stack2时加一个判断,如果stack2中不为空,那么显然此时是不能压入stack2的。
方法一:每次多了一个压入stack1的过程,九度OJ超时:
#include <stdio.h>#include <iostream>#include <stack>#include <string>using namespace std;int main(){ // freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin); int m; while(cin>>m) { stack<int> a,b; string mdo; int mid; for(int i=0;i<m;i++) { cin>>mdo; if(mdo=="PUSH") { cin>>mid; a.push(mid); } else { while(!a.empty()) { b.push(a.top()); a.pop(); } if(b.empty()) { cout<<"-1"<<endl; } else { cout<<b.top()<<endl; b.pop(); } while(!b.empty()) { a.push(b.top()); b.pop(); } } } } return 0;}
方法二:
#include <stdio.h>#include <iostream>#include <stack>#include <string>using namespace std;int main(){ //freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin); int m; while(cin>>m) { stack<int> a,b; string mdo; int mid; for(int i=0;i<m;i++) { cin>>mdo; if(mdo=="PUSH") { cin>>mid; a.push(mid); } else { if(b.empty()) while(!a.empty()) { b.push(a.top()); a.pop(); } if(b.empty()) { cout<<"-1"<<endl; } else { cout<<b.top()<<endl; b.pop(); } } } } return 0;}
0 0
- 剑指Offer之用两个栈实现队列
- 剑指Offer之 - 用两个栈实现队列
- 剑指offer之用两个栈实现队列
- 剑指offer系列之五:用两个栈实现队列
- 剑指offer面试题之用两个栈实现队列
- 剑指offer(二)之用两个栈实现队列
- (五)剑指offer之用两个栈实现队列
- 剑指offer之用两个栈实现队列
- 剑指offer之用两个栈实现队列
- 剑指offer之四---用两个栈实现队列
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- Xshell工具连接linux系统笔记
- C# DataTable转json,DataSet转json
- 在mac上解决Android sdk content loader 0%的问题
- iOS开发之获取系统相册中的图片与视频(内带url转换)
- 自动化代码分析的过去、现状和将来
- 剑指Offer之用两个栈实现队列
- C++之typedef
- Linux中一些命令
- Linux下JNI的调用
- 丑八怪
- 【持续更新】C++里的一些特性
- snmp++开发实例一
- cocos2d-x之怪物系统
- ·老板娘,你的小内裤也穿外面吗