算法练习-LeetCoe 232. Implement Queue using Stacks

题目地址:https://leetcode.com/problems/implement-queue-using-stacks/

解题思路:双stack(一进一出)

解题代码:java

class MyQueue {
    Stack<Integer> front;
    Stack<Integer> backend;
    public MyQueue() {
        front = new Stack<>();
        backend = new Stack<>();        
    }
    
    public void push(int x) {
        while(!backend.isEmpty()){
            front.push(backend.pop());
        }
        front.push(x);
    }
    
    public int pop() {
        while(!front.isEmpty()){
            backend.push(front.pop());
        }
        return backend.pop();
    }
    
    public int peek() {
        int res = pop();
        backend.push(res);
        return res;
    }
    
    public boolean empty() {
        return front.isEmpty() && backend.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();
 */

思路解释:

push: queue 要求先进先出,stack的push和pop实现的是先进后出

如果front先进,backend为front栈pop的结果

开始时,backend为空,直接将x押入front;当backend栈有东西的时候,将backend中东西压入front,之后再将x 值 push 进去,保证之后到backend 的时候顺序是正确的。

    public void push(int x) {
        while(!backend.isEmpty()){
            front.push(backend.pop());
        }
        front.push(x);
    }

Pop:

开始时有值push进front,front不为空,将font的东西压入backend,实现顺序调换,然后pop出最先压入进来的值。注意:此时已经将front里面的所所有值都pop到backend里面了,也就是说front此时为空。

    public int pop() {
        while(!front.isEmpty()){
            backend.push(front.pop());
        }
        return backend.pop();
    }

Peek:

调用MyQueue的pop,弹出的值就是最先进入的值,随后又push回backend。

   public int peek() {
        int res = pop();
        backend.push(res);
        return res;
    }

empty:

要保证font和backend里面均没有值的时候,MyQueue才是empty的。

  public boolean empty() {
        return front.isEmpty() && backend.isEmpty();
    }

猜你喜欢

转载自blog.csdn.net/qq_41758969/article/details/129214323