LeetCode 232. Implement Queue using Stacks
2016-04-04 20:31
549 查看
和225类似,queue和stack的性质正好相反,因此在push时要进行处理。
维护两个stack:stk和tmp,stk存放与queue相反的顺序,比如queue为:1、4、5,stk为:5、4、1,这样stk.top()会一直等于queue.front()。
每次push进一个数x时,先把stk内的数全push进tmp中,再把x压入stk,最后把tmp中的数全push进stk,这样就保证了x在stk的栈底。
维护两个stack:stk和tmp,stk存放与queue相反的顺序,比如queue为:1、4、5,stk为:5、4、1,这样stk.top()会一直等于queue.front()。
每次push进一个数x时,先把stk内的数全push进tmp中,再把x压入stk,最后把tmp中的数全push进stk,这样就保证了x在stk的栈底。
class Queue { public: // Push element x to the back of queue. void push(int x) { while(!stk.empty()){ tmp.push(stk.top()); stk.pop(); } stk.push(x); while(!tmp.empty()){ stk.push(tmp.top()); tmp.pop(); } } // Removes the element from in front of queue. void pop(void) { stk.pop(); } // Get the front element. int peek(void) { return stk.top(); } // Return whether the queue is empty. bool empty(void) { return stk.empty(); } private: stack<int> stk, tmp; };
相关文章推荐
- 【VK Cup 2016 - Round 1 (Div 2 Edition)E】【目标线思想差值相减 优先队列】Bear and Contribution c5成本+5 c1成本+1使得至少k人贡献相
- LeetCode 225. Implement Stack using Queues
- 设置request.setCharacterEncoding()后,servlet中文乱码问题
- IOS-- UIView中的坐标转换
- UICollectionView用法补充(照片轮播墙)
- UDID、UUID+keychain
- 在Java8的foreach()中使用return/break/continue
- HDU 3279 Nth Largest Value
- Leetcode232. Implement Queue using Stacks[栈实现队列]
- ios--uitextfield动态限制输入的字数(解决方式)
- 3.30课·········Marquee标签
- Hive分析窗口函数之LAG,LEAD,FIRST_VALUE和LAST_VALUE
- CALayer 的基本概念和基本使用
- This certificate has an invalid issuer
- BlockingQueue队列学习
- 关于requirejs中的define的原理理解
- 【HDU 2604】 Queuing
- cryptoAPI接口(五)------------获取证书--演示 CryptUIDlgViewCertificate
- key-value store
- String StringBuilder StringBuffer