剑指offer题五
来源:互联网 发布:解忧杂货店淘宝 编辑:程序博客网 时间:2024/05/18 16:14
package jianzhioffer;import java.util.ArrayList;import java.util.List;import java.util.Stack; /** * 用两个栈实现队列的出入栈,栈A用来作入队列,栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列) * */public class StacktoQueue { 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(); } public static void main(String[] args) {StacktoQueue sq = new StacktoQueue();List<Integer> list = new ArrayList<Integer>();sq.push(1);sq.push(2);sq.push(3);list.add(sq.pop());sq.push(4);list.add(sq.pop());sq.push(5);list.add(sq.pop());list.add(sq.pop());list.add(sq.pop());System.out.println(list.toString());} }
package jianzhioffer;import java.util.LinkedList;import java.util.Queue;/** * 两个队列实现一个栈 出入功能 * */public class QueuetoStack { LinkedList<Integer> queue1 = new LinkedList<Integer>();LinkedList<Integer> queue2 = new LinkedList<Integer>();public Integer pop(){Integer re = null;if(queue1.size() ==0 && queue2.size() ==0){return null;}if(queue2.size()==0){while(queue1.size()>0){re=queue1.removeFirst();if(queue1.size()!=0){//do not add the last element of queue1 to queue2 queue2.addLast(re);}}}else if (queue1.size() ==0){while(queue2.size()>0){re = queue2.removeFirst();if(queue2.size() != 0){//do not add the last element of queue2 to queue1 queue1.addLast(re);}}}return re;}public Integer push(Integer node){if(queue1.size() == 0 && queue2.size() == 0){queue1.addLast(node);}if(queue1.size() != 0){queue1.addLast(node);}else if(queue2.size() != 0){queue2.addLast(node);}return node;}public static void main(String[] args) {QueuetoStack qs = new QueuetoStack();int tmp = 0;qs.push(1);qs.push(2);qs.push(3);tmp = qs.pop();System.out.println(tmp);//3qs.push(4);tmp = qs.pop();System.out.println(tmp);//4qs.push(5);qs.push(6);tmp = qs.pop();System.out.println(tmp);//6tmp = qs.pop();System.out.println(tmp);//5tmp = qs.pop();System.out.println(tmp);//2tmp = qs.pop();System.out.println(tmp);//1}}
阅读全文
0 0
- 剑指offer题五
- 剑指offer 五
- 剑指offer(五)
- 剑指offer(五)之跳台阶
- 剑指offer之编程(五)
- 剑指offer经典编程(五)
- 剑指Offer-五只猴子吃桃子
- 剑指offer 练习五(Java版)
- 剑指Offer编程整理(五)
- 牛客网 剑指Offer,一些值得记住的小题(五)
- 剑指offer系列之五:用两个栈实现队列
- 《剑指offer》:[56]五岔路口交通管理红绿灯设计
- (五)剑指offer之用两个栈实现队列
- 剑指Offer题目JAVA版思路与代码(五)
- 剑指offer(五)两个栈实现队列
- 剑指offer之五---旋转数组的最小数字
- 剑指Offer(五)用两个栈实现队列
- 剑指offer第一题
- 大学最后的暑假开始
- Java类加载器加载类的过程
- 【Salesforce】(Tips) 外部APIで取得したPDFファイルをVisualforceで表示する
- php基础总结
- MVP的立即
- 剑指offer题五
- P2746 [USACO5.3]校园网Network of Schools
- Linux中free命令详解
- java多线程之yield
- Android属性动画完全解析(下),Interpolator和ViewPropertyAnimator的用法
- KOA2 提供HTTPS安全服务
- Android面试-Java基础-基本语法
- log4j.properties 配置
- eclipse导入myeclipse的web项目没法识别问题解决