题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
栈的特点是先进后出,而队列的特点是先进先出。问题是如何把栈的出栈和入栈与队列的入队和出队联系起来?因为现在只有栈,所以在实现的队列中,只能先往栈中添加元素,这点比较好理解;那么出队呢,由于先进去的元素被压在栈底,而如果是队列的话,必须是栈底的那个元素先出队。现在可以使用第二个栈,思路是把原先第一个栈中的元素出栈,并压入第二个栈中,观察第二个栈,就可以发现:在第二个栈中的元素顺序与正常队列出队的顺序是一致的了。所以这样,问题就解决了。
package com.gpl.offer.jianzhi;
import java.util.Stack;
/**
* Created by gpl on 2016/8/3.
*/
public class Stack2Queue {
Stack<Integer> stack1 = null;
Stack<Integer> stack2 = null;
public Stack2Queue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void inQueue(int i){
stack1.push(i);
}
public int outQueue(){
if(stack2.isEmpty()){
while(!stack1.isEmpty())
stack2.push(stack1.pop());
}
if(stack2.isEmpty()){
try{
throw new Exception("empty queue");
}catch(Exception e){
e.printStackTrace();
}
}
return stack2.pop();
}
public static void main(String[] args){
Stack2Queue sq = new Stack2Queue();
sq.inQueue(1);
sq.inQueue(2);
sq.inQueue(3);
System.out.println(sq.outQueue());
System.out.println(sq.outQueue());
System.out.println("stack1大小:"+sq.stack1.size());
System.out.println("stack2大小:"+sq.stack2.size());
sq.inQueue(4);
System.out.println("stack1大小:"+sq.stack1.size());
System.out.println(sq.outQueue());
System.out.println(sq.outQueue());
}
}