面试题7:用两个栈实现队列+用两个队列实现栈
2016-01-11 10:59
525 查看
算法思想(用两个栈实现队列):
代码如下:
算法思想(用两个队列实现栈):
代码如下:
代码如下:
import java.util.Stack; public class Demo7_1 { private Stack<String> stack1 = new Stack<String>(); private Stack<String> stack2 = new Stack<String>(); public void appendTail(String s){ stack1.push(s); } public String deleteHead() throws Exception{ if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } if(stack2.isEmpty()){ throw new Exception("队列为空,不能删除"); } return stack2.pop(); } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Demo7_1 demo=new Demo7_1(); demo.appendTail("1"); demo.appendTail("2"); demo.appendTail("3"); System.out.println(demo.deleteHead()); System.out.println(demo.deleteHead()); System.out.println(demo.deleteHead()); } }
算法思想(用两个队列实现栈):
代码如下:
import java.util.LinkedList; public class Demo7_2 { //tail in head out 1 2 3 private LinkedList<String> queue1 = new LinkedList<String>(); private LinkedList<String> queue2 = new LinkedList<String>(); public void push(String s){ if(queue1.size()==0 && queue2.size()==0){ queue1.addLast(s); } if(queue1.size()!=0){ queue1.addLast(s); }else if(queue2.size()!=0){ queue2.addLast(s); } } public String pop(){ String s=null; if(queue1.size()==0 && queue2.size()==0){ return null; } if(queue2.size()==0) { while(queue1.size()>0) { s=queue1.removeFirst();//3从queue1中删除 if(queue1.size()!=0) { queue2.addLast(s);//1 2 进入queue2 } } } else if(queue1.size()==0) { while(queue2.size()>0) { s=queue2.removeFirst(); if(queue2.size()!=0) { queue1.addLast(s); } } } return s; } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Demo7_2 demo=new Demo7_2(); demo.push("1"); demo.push("2"); demo.push("3"); System.out.println(demo.pop()); System.out.println(demo.pop()); System.out.println(demo.pop()); } }
相关文章推荐
- 黑马程序员——iOS 开发学习---登录注册页面跳转
- 三招搞定群体面试
- 面试题3:二维数组中的查找
- 我是如何准备ThoughtWorks面试的
- 程序员
- 程序员遇到BUG后,最好的方法是?
- ios面试题(附答案)
- 这个寒冬,如何赶走职场之“霾”
- 面试题
- 黑马程序员——正则篇
- 有人说中文编辑是解决中国程序员编程效率的秘密武器,请问他是一个银弹吗?
- 黑马程序员——数组篇
- 面试经历---广州金砖信息技术有限公司(2015年11月25日上午面试)
- 面试经历---YY欢聚时代(2015年11月21日上午初试、25日下午复试)
- android 面试题
- .NET反编译的九大金刚
- 每一个程序员都应当了解的11句话
- 「程序员思维训练」2. 具体计划
- 截止2016年1月已取消的207项职业资格许可和认定事项
- LeetCode208. Implement Trie (Prefix Tree)实现前缀树