lintcode: Implement Queue by Two Stacks
2016-03-25 17:55
225 查看
Description
Notes
Testcase
Judge
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support
pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Have you met this question in a real interview?
Yes
Example
Challenge
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.
Notes
Testcase
Judge
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support
push(element),
pop()and
top()where
pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Have you met this question in a real interview?
Yes
Example
push(1) pop() // return 1 push(2) push(3) top() // return 2 pop() // return 2
Challenge
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.
class Queue { public: stack<int> stack1; stack<int> stack2; Queue() { // do intialization if necessary } void push(int element) { // write your code here while (stack2.size() > 0) { stack1.push(stack2.top()); stack2.pop(); } stack1.push(element); } int pop() { while (stack1.size() > 0) { stack2.push(stack1.top()); stack1.pop(); } if (stack2.size() > 0) { int tmp = stack2.top(); stack2.pop(); return tmp; } return -1; // write your code here } int top() { while (stack1.size() > 0) { stack2.push(stack1.top()); stack1.pop(); } if (stack2.size() > 0) { return stack2.top(); } return -1; // write your code here } };
相关文章推荐
- uint8、double、mat2uint、imhist绘直方图w恩替藐视
- JAVA顺序表(Sequential List)操作
- Android4.42-Setting源码分析之蓝牙模块Bluetooth(下)
- 使用SOAPUI测试WEBAPI接口
- web UI技术方案备忘
- 能否在非UI线程更新界面呢?
- Hootsuite(互随社交)
- PreferenceActivity 中的 onBuildHeaders() 调用时机
- Hootsuite(互随社交)
- Hootsuite(互随社交)
- leetcode之Repeated DNA Sequences
- Generate a hash from unique ID
- [leetcode] 272. Closest Binary Search Tree Value II 解题报告
- 五种创建UIImage的类方法
- 关于easyUI的combbobox下拉框多选时,后台获取下拉框的值获取的问题
- ios学习总结(2) -- UIButton的使用
- ios学习总结(2) -- UIButton的使用
- UESTC 1271 Search gold
- ios学习总结(2) -- UIButton的使用
- UIViewController - SenDylan