剑指offer 用2个栈实现队列
来源:互联网 发布:php高级编程书籍 编辑:程序博客网 时间:2024/06/05 19:19
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解决方案:
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(new Integer(node)); } public int pop() { Integer r=null; if(!stack2.isEmpty()){ r=stack2.pop();//如果stack2不是空的,则弹出第一个 //写上面一句的重要性:当多次弹出的时候,就要执行这一句 }else{ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } if(!stack2.isEmpty()){ r=stack2.pop(); } } return r; }}
或者
这是左程云的《程序员代码面试指南》的答案: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() { if(stack1.empty()&&stack2.empty()){ throw new RuntimeException("Queue is empty!"); } if(stack2.empty()){ while(!stack1.empty()){ stack2.push(stack1.pop()); } } return stack2.pop(); }}
阅读全文
0 0
- 剑指offer 用2个栈实现队列
- [剑指offer]算法5 两个栈实现1个队列
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- 【剑指Offer】用两个栈实现队列
- 剑指offer-用两个栈实现队列
- 《剑指offer》-用两个栈实现队列
- 剑指offer 用两个栈实现队列
- 剑指offer 用两个栈实现队列
- [剑指offer]用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指offer|用两个栈实现队列
- java中stringBuilder的用法
- 韩红爱心基金会联合有宠成立“有宠有爱专项公益基金”
- 创新单屏分分钟刷出精彩 QQ浏览器6.4版上线
- 为什么说扫地机器人要智能导航
- 寻找大富翁(25 分)
- 剑指offer 用2个栈实现队列
- JVM类加载机制
- JAVA CAS原理深度分析
- 小知“媒体人+”沙龙:与媒体大咖聊聊创业的那些事
- 奥运排行榜(25 分)
- 腾讯官方“抢红包神器”上线 春节抢红包安全又神速
- 好闲置,一款专做女性精品闲置交易的APP
- 二维扫码平台经济开启,湖南中烟搭乘“顺风车”
- 系统虚拟机的快照 镜像