使用两个栈实现队列

/*
 * @Time : 12/24/2018 21:38
 * @Author : Zhang, Chen (chansonzhang)
 * @Email : ZhangChen.Shaanxi@gmail.com
 * @FileName: DoubleStackQueue.java
 */
public class DoubleStackQueue<T> {
    private Stack<T> stackIn;
    private Stack<T> stackOut;

    public DoubleStackQueue(){
        stackIn=new Stack<>();
        stackOut=new Stack<>();
    }

    public T push(T x){
        stackIn.push(x);
        return x;
    }

    public T pop(){
        shiftStack();
        return stackOut.pop();
    }

    public boolean isEmpty(){
        return 0==stackIn.size() && 0==stackOut.size();
    }

    private void shiftStack(){
        if(stackOut.empty()) {
            while (!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }
        }
    }

    public static void main(String[] args){
        DoubleStackQueue<Integer> myQueue=new DoubleStackQueue<>();
        for(int i=0;i<10;i++){
            myQueue.push(i);
        }
        while (!myQueue.isEmpty()){
            System.out.print(myQueue.pop()+" ");
        }

        System.out.println();
        myQueue.push(0);
        myQueue.push(1);
        myQueue.push(2);
        System.out.print(myQueue.pop()+" ");
        myQueue.push(3);
        myQueue.push(4);
        myQueue.push(5);

        while (!myQueue.isEmpty()){
            System.out.print(myQueue.pop()+" ");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值