如何用两个栈实现队列

import java.util.Stack;

public class QueueTest {

    private Stack<Integer> inStack=new Stack<>();
    private Stack<Integer> outStack=new Stack<>();
    /**
     * 
     * @Description: (入栈) 
     * @author: liyhui
     * @date: 2018年11月24日
     * @param ele
     */
    public void enQueue(int ele ) {
        inStack.push(ele);
    }
    /**
     * 
     * @Description: (出栈) 
     * @author: liyhui
     * @date: 2018年11月24日
     * @param ele
     */
    public Integer deQueue( ) {
        if(outStack.isEmpty()) {
            if(inStack.isEmpty()) {
                return null;
            }
            this.transfer();
        }
        return outStack.pop();
    }
    /**
     * 
     * @Description: (将入栈的元素给出栈) 
     * @author: liyhui
     * @date: 2018年11月24日
     */
    private void transfer() {
        while(!inStack.isEmpty()) {
            outStack.push(inStack.pop());
        }        
    }
    
    public static void main(String[] args) {
        QueueTest test=new QueueTest();
        test.enQueue(1);
        test.enQueue(2);
        test.enQueue(3);
        
        System.out.println(test.deQueue());
        test.enQueue(4);
        System.out.println(test.deQueue());
        System.out.println(test.deQueue());
        System.out.println(test.deQueue());
    }
}

 

posted @ 2018-11-24 15:30  冬马党  阅读(167)  评论(0编辑  收藏  举报