225. 用队列实现栈

传送门

代码

class MyStack {
    Queue<Integer> que1;
    Queue<Integer> que2;
    /** Initialize your data structure here. */
    public MyStack() {
        que1 = new LinkedList<>();
        que2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        que1.offer(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        int size = que1.size();
        for(int i = 0;i < size - 1; ++i) {
            que2.offer(que1.poll());
        }
        int val = que1.poll();
        while(!que2.isEmpty()) {
            que1.offer(que2.poll());
        }
        return val;
    }
    
    /** Get the top element. */
    public int top() {
        int _top;
        int size = que1.size();
        for(int i = 0;i < size - 1; ++i) {
            que2.offer(que1.poll());
        }
        _top = que1.poll();
        que2.offer(_top);
        while(!que2.isEmpty()) {
            que1.offer(que2.poll());
        }
        return _top;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return que1.isEmpty();
    }
}

思路

用两个队列实现一个栈

\(que1\) 当主队列,\(que2\) 当辅助队列

添加元素都往\(que1\) 上添加,

删除元素或者,查看栈顶元素的时候,就把\(que1\) 全部倒出来,先暂放到 \(que2\) 中,最后在倒回去\(que1\) 中即可

posted @ 2021-01-01 19:37  南风--  阅读(61)  评论(0编辑  收藏  举报