leetcode232. 用栈实现队列

leetcode232. 用栈实现队列,第1张

1.题目描述:

2.解法:(关键在于使用两个栈进行模拟)

class MyQueue {
    Stack stackIn = new Stack<>();//入栈 *** 作
    Stack stackOut = new Stack<>();//出栈 *** 作
    public MyQueue() {

    }
    
    public void push(int x) {
        stackIn.push(x);
    }
    
    public int pop() {
        reverse();
        return stackOut.pop();
    }
    
    public int peek() {
        reverse();
        return stackOut.peek();
    }
    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }

    public void reverse() {
        if (!stackOut.isEmpty()) return;
        //一旦涉及pop、push就会调用;但是一旦出栈的栈中有元素,
        //则不把入栈的元素放入(否则破环队列的先进先出),直到出栈的元素为空再入
        while (!stackIn.isEmpty()) {
            stackOut.push(stackIn.pop());
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/924134.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存