[剑指offer]面试题 7:用两个栈实现队列

面试题 7:用两个栈实现队列

tag: stack queue 栈与队列的互转

leetcode: 232. 用栈实现队列

public class MyQueue {
    // 使用两个栈,利用栈的后进先出,实现队列的先进先出
    Stack<Integer> inQueue;
    // 出栈队列
    Stack<Integer> outQueue;

    // 只有构造类的时候才创建对象
    public MyQueue() {
        this.inQueue = new Stack<>();
        this.outQueue = new Stack<>();
    }

    // 压入元素
    public void push(int x) {
        // 入队,仅放入入队队列
        inQueue.push(x);
    }

    // 弹出,先看出队队列有没有,要短路阶段,减少判断
    // Removes the object at the top of this stack and returns that object as the value of this function
    public int pop() {
        // 所有复杂数据结构在使用前都要进行非空判断
        if (!outQueue.isEmpty()) {
            return outQueue.pop();
        }

        if (!inQueue.isEmpty()) {
            // 对队列等的循环,最好要while
            while (!inQueue.isEmpty()) {
                outQueue.push(inQueue.pop());
            }

            return outQueue.pop();
        }

        // 都为空,返回
        return -1;
    }

    // Looks at the object at the top of this stack without removing it from the stack
    public int peek() {
        // peek不是弹出,检视
        if (!outQueue.isEmpty()) {
            return outQueue.peek();
        }
        if (!inQueue.isEmpty()) {
            // 对队列等的循环,最好要while
            while (!inQueue.isEmpty()) {
                outQueue.push(inQueue.pop());
            }

            return outQueue.peek();
        }

        return -1;
    }

    public boolean empty() {
        return outQueue.isEmpty() && inQueue.isEmpty();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值