225. 用队列实现栈

115 阅读1分钟

class MyStack {
    Queue<Integer> queue = new LinkedList<>();
    Queue<Integer> helper = new LinkedList<>();

    public MyStack() {
        
    }
    
    public void push(int x) {
        queue.offer(x);
    }
    
    public int pop() {
        int tmp = 0;
        while (queue.size() > 1) {
            tmp = queue.poll();
            helper.offer(tmp);
        }
        //栈要pop的那个元素,即队尾,不再放入helper队列,只poll
        tmp = queue.poll();
        //helper转到queue中
        while(!helper.isEmpty()) {
            queue.offer(helper.poll());
        }
        return tmp;
    }
    
    public int top() {
        int tmp = 0;
        while (!queue.isEmpty()) {
            tmp = queue.poll();
            helper.offer(tmp);
        }
        //helper转到queue中
        while(!helper.isEmpty()) {
            queue.offer(helper.poll());
        }
        return tmp;
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
}