Lintcode 用栈实现队列
来源:互联网 发布:mac迅雷速度为0 编辑:程序博客网 时间:2024/05/17 01:49
用栈实现队列
正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。
开始直观的想法:
`
class Queue {
public:
stack stack1;
stack stack2;
Queue() { // do intialization if necessary}void push(int element) { // write your code here stack1.push(element);}int pop() { // write your code here if(stack1.empty()) return -1; while(!stack1.empty()){ int num = stack1.top(); stack1.pop(); stack2.push(num); } //operate pop() int value = stack2.top(); stack2.pop(); while(!stack2.empty()){ int num = stack2.top(); stack2.pop(); stack1.push(num); } return value;}int top() { // write your code here if(stack1.empty()) return -1; while(!stack1.empty()){ int num = stack1.top(); stack1.pop(); stack2.push(num); } //operate top() int value = stack2.top(); while(!stack2.empty()){ int num = stack2.top(); stack2.pop(); stack1.push(num); } return value;}
};
`
挑战:仅使用两个栈来实现它,不使用任何其他数据结构,push,pop 和 top的复杂度都应该是均摊O(1)的
class Queue {
public:
stack stack1;
stack stack2;
Queue() { // do intialization if necessary}void push(int element) { // write your code here stack1.push(element);}int pop() { // write your code here if(stack1.empty()&&stack2.empty()) return -1; if(stack2.empty()){ while(!stack1.empty()){ int num = stack1.top(); stack1.pop(); stack2.push(num); } } int value = stack2.top(); stack2.pop(); return value;}int top() { // write your code here if(stack1.empty()&&stack2.empty()) return -1; if(stack2.empty()){ while(!stack1.empty()){ int num = stack1.top(); stack1.pop(); stack2.push(num); } } int value = stack2.top(); return value;}
};
0 0
- Lintcode 用栈实现队列
- LintCode:用栈实现队列
- 【LintCode】用栈实现队列
- LintCode : 用栈实现队列
- lintcode,用栈实现队列
- Lintcode 用栈实现队列
- Lintcode 用栈实现队列
- lintcode-用栈实现队列-40
- [Lintcode]用栈实现队列
- LintCode 40 用栈实现队列
- [LintCode]40.用栈实现队列
- LintCode之40 用栈实现队列
- LintCode-剑指Offer-(40)用栈实现队列
- 用栈实现队列
- 用队列实现栈
- 用栈实现队列
- 用队列实现栈
- 用栈实现队列
- js原生的ajax写法
- 线段树 && 树状数组
- 通过只调整指针(而不是数据)来交换两个相邻的元素
- 使用yum只获取rpm包不自动安装
- Constructing Roads
- Lintcode 用栈实现队列
- hdu1754线段树单点更新
- MyBatis初级环境搭建
- Leetcode:303. Range Sum Query - Immutable(JAVA)
- 常见http状态码详解
- Improved SLIC 算法学习笔记
- css居中控制 水平居中 垂直居中
- Eclipse 乱码 解决方案总结(UTF8 -- GBK)
- CentOS7.2共享文件夹_安装配置SAMBA服务器