🌗 232. 用栈实现队列

吞佛童子2022年6月20日
  • algorithm
  • queue
  • stack
小于 1 分钟

🌗 232. 用栈实现队列

难度: 🌗

问题描述

img_1.png


解法

class MyQueue {
    LinkedList<Integer> stack1;
    LinkedList<Integer> stack2;

    public MyQueue() {
        stack1 = new LinkedList<>();
        stack2 = new LinkedList<>();
    }
    
    public void push(int x) {
        stack1.push(x);
    }
    
    public int pop() {
        // 将 stack1 中的元素依次压入 stack2
        while(!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
        // stack2 栈顶元素为 队列头元素
        int res = stack2.pop();
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        return res;
    }
    
    public int peek() {
        // 将 stack1 中的元素依次压入 stack2
        while(!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
        // stack2 栈顶元素为 队列头元素
        int res = stack2.peek();
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        return res;
    }
    
    public boolean empty() {
        return stack1.isEmpty();
    }
}

/**
 * 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();
 */

输出

img.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou