剑指Offer07-两个栈实现队列
两个栈实现队列的思路:
队列的特点是的先进先出;
栈的特点是先进后出;
将数据存入栈1,再按其输出的特点存入栈2;
这样数据最后就可以实现先进先出的特点;
代码实现:
import java.util.Stack; public class No7 { public static void main(String[] args) { No7 queue = new No7(); queue.offer(1); queue.offer(2); queue.offer(3); queue.poll(); queue.poll(); queue.poll(); } private Stack s1 = new Stack(); private Stack s2 = new Stack(); //实现队列的的offer方法:将元素加入到队列的末尾 public void offer(Object x) { s1.push(x); } public void poll() { if(s1.size()==0 && s2.size()==0 ) { try { throw new Exception("队列为空"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if(s2.size()!=0) { System.out.println(s2.peek().toString()); s2.pop(); } else { //将s1的数据赋值给s2 while(s1.size()>0) { s2.push(s1.pop()); } System.out.println(s2.peek().toString()); s2.pop(); } } } }