0
点赞
收藏
分享

微信扫一扫

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

自由情感小屋 2022-02-01 阅读 25

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

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

相关推荐

0 条评论