【剑指offer-Java版】07用两个栈实现队列
来源:互联网 发布:cf自瞄脚本源码 编辑:程序博客网 时间:2024/05/21 18:48
两个栈实现一个队列:stack_1 stack_2
入队操作:直接入stack_1
出队操作:如果stack_2不为空,那么从其中弹出一个作为出队元素,否则将stack_1元素全部依次压入stack_2然后弹出顶层
队满状态:stack_1和stack_2都满
队空状态:stack_1和stack_2都空
边界条件没有怎么考虑
public class _Q07 { private Stack<Integer> stack_1 = new Stack<>(); private Stack<Integer> stack_2 = new Stack<>(); public void enQueue(int val){ stack_1.push(val); } public int deQueue() throws Exception{ if(stack_2.isEmpty()){ while(!stack_1.isEmpty()){ stack_2.push(stack_1.pop()); } } if(stack_2.isEmpty()){ throw new Exception("no item in queue"); } return stack_2.pop(); } }
测试代码:
public class _Q07Test extends TestCase { _Q07 queue = new _Q07(); public void testQueue() throws Exception{ queue.enQueue(1); queue.enQueue(3); queue.enQueue(2); queue.enQueue(4); for(int i=0; i<4; i++){ System.out.println(queue.deQueue()); } } }
1 0
- 【剑指offer-Java版】07用两个栈实现队列
- 《剑指offer》用两个队列实现栈 Java版实现
- 剑指offer-----用两个栈实现队列(java版)
- 剑指offer-Java-用两个栈实现队列
- 【剑指offer】 用两个栈实现队列 -Java
- 《剑指offer》牛客网java题解-用两个栈实现队列
- 剑指offer:用两个栈实现队列、用两个队列实现一个栈(java)
- 剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈
- 剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈
- 剑指offer-07:两个栈实现队列
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- 简单的SVG线条动画
- Android学习之友盟5.0推送,分享踩坑总结
- [event] 2016 openIoT Summit
- BOM新成就(1)--客户端存储数据(Storage实现)
- 邻接表非递归广搜(有向图)
- 【剑指offer-Java版】07用两个栈实现队列
- Spring Security3实践总结
- Ubuntu安装Android Studio出现错unable to run mksdcard sdk tool
- iOS公钥 私钥原理以及相关资源
- Java读带有BOM的UTF-8文件乱码原因及解决方法
- h264 写入文件时“wb+”
- linux sqlite 安装编译问题
- iOS 2D 绘图(Quartz2D)
- 汽车分类——多元分类