LintCode 40 用栈实现队列
来源:互联网 发布:数据库修改语句例题 编辑:程序博客网 时间:2024/06/05 19:43
题目:MyQueue
要求:
正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。
样例:
比如push(1), pop(), push(2), push(3), top(), pop(),你应该返回1,2和2
算法要求:
仅使用两个栈来实现它,不使用任何其他数据结构,push,pop 和 top的复杂度都应该是均摊O(1)的
解题思路:
就是要理解,栈是先进后出,那么一个栈pop到另一个栈,那么另一个栈pop就相当于先进先出
算法如下:
class MyQueue {public: stack<int> stack1; stack<int> stack2; MyQueue() { } void push(int element) { stack1.push(element); } int pop() { if (stack2.empty()) { lTor(); } if (stack2.empty()) { throw -1; } else { int temp = stack2.top(); stack2.pop(); return temp; } } void lTor() { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } int top() { if (stack2.empty()) { lTor(); } if (stack2.empty()) { throw -1; } else { return stack2.top(); } }};
0 0
- lintcode-用栈实现队列-40
- LintCode 40 用栈实现队列
- LintCode之40 用栈实现队列
- Lintcode 用栈实现队列
- LintCode:用栈实现队列
- 【LintCode】用栈实现队列
- LintCode : 用栈实现队列
- lintcode,用栈实现队列
- Lintcode 用栈实现队列
- Lintcode 用栈实现队列
- LintCode-剑指Offer-(40)用栈实现队列
- [Lintcode]用栈实现队列
- [LintCode]40.用栈实现队列
- 用栈实现队列
- 用队列实现栈
- 用栈实现队列
- 用队列实现栈
- 用栈实现队列
- ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法
- PAT甲级1004CountingLeaves
- Java使用DOM解析XML的文件属性名和属性值、节点名和节点值
- jQuery 事件中 bind 方法和blur() 方法
- 51nod_1081 子段求和
- LintCode 40 用栈实现队列
- curator中监听器的实现
- poj 2369 Permutations (置换群入门)
- 《城市交通大数据》读书总结
- LeetCode-algorithms 47. Permutations II
- 简单迷宫算法实现
- 数据库常用命令
- Tomcat 8.5 400错误:Invalid character found in the request target. 问题解决方法
- 3. Longest Substring Without Repeating Characters