其他分享
首页 > 其他分享> > 【2022初春】【LeetCode】232. 用栈实现队列

【2022初春】【LeetCode】232. 用栈实现队列

作者:互联网

一遍过了,中间差一个判断

class MyQueue {
    Stack<Integer> a;
    Stack<Integer> b;
    public MyQueue() {
        a = new Stack<Integer>();
        b = new Stack<Integer>();
    }
    
    public void push(int x) {
        a.push(x);
        if(b.isEmpty()) b.push(x);
    }
    
    public int pop() {
        int ans = b.pop();
        if(b.isEmpty()&&!a.isEmpty()){
            while(!a.isEmpty()){
                b.push(a.peek());
                a.pop();
            }
            if(b.peek()==ans) b.pop();
        }
        return ans;
    }
    
    public int peek() {
        return b.peek();
    }
    
    public boolean empty() {
        if(a.isEmpty()&&b.isEmpty()) return true;
        else return false;
    }
}

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

标签:peek,int,pop,public,用栈,isEmpty,2022,MyQueue,LeetCode
来源: https://blog.csdn.net/mdzz_z/article/details/122766713