两个栈实现一个队列
2016-05-06 10:54
435 查看
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
1.
2.
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
1.
class Solution { public: void push(int node) { //入队时,将元素压入s1。 //出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。 //这个思路,避免了反复“倒”栈,仅在需要时才“倒”一次。 stack1.push(node) ; } int pop() { int tmp; if(stack2.empty()){ while(stack1.empty()!=1){ tmp=stack1.top(); //stack1.pop() 删除栈顶元素但不返回其值 stack1.pop(); stack2.push(tmp); } } tmp=stack2.top(); stack2.pop(); return tmp; //返回队首元素 } private: stack<int> stack1; stack<int> stack2; };
2.
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { int tmp; if(stack2.isEmpty()){ while(stack1.isEmpty()!=true){ tmp=stack1.peek(); stack1.pop(); stack2.push(tmp); } } tmp=stack2.peek(); stack2.pop(); return tmp; } }
相关文章推荐
- matlab gui画图笔记
- 一站式学习Wireshark(四):网络性能排查之TCP重传与重复ACK
- 【C++】类的静态数据成员
- 全面推进云化,使能数字化转型 ——徐直军在2016华为全球分析师大会上的发言
- Android如何设置Activity全屏
- Z-Stack 的应用层参数修改
- 归并排序求逆序数(排序算法)
- 1.2 大型网站架构演化发展过程[读书敲录]
- 学会用各种姿势备份MySQL数据库
- 第二天:让我们一起来玩玩css精灵(css sprites)
- Curator leader 选举(一)
- Java关键字 ClassName.this(类名.this)的理解
- Delphi 10.1 Berlin UTF8String Test
- 【Linux程序员福音】在Visual Studio上用C++写Linux
- web3.0技术的发展与应用
- 神奇的android:clipChildren属性
- Responsive Nav
- 十进制与二进制相互转换
- 单链表的逆置
- makefile---include的使用