0255. Implement Stack Using Queues

0255. Implement Stack using Queues #

题目 #

  • 使用两个队列实现一个后入先出的栈,支持普通栈的全部四种操作。
  • 实现 MyStack 类:
    • void push(int x) 将元素 x 压入栈顶。
    • int pop() 移除并返回栈顶元素。
    • int top() 返回栈顶元素。
    • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

思路 #

使用两个队列实现栈 #

代码 #

使用两个队列实现栈 #

class MyStack {
    private Queue<Integer> stack, queue;
    
    public MyStack() {
        this.stack = new LinkedList<>();
        this.queue = new LinkedList<>();
    }
    
    public void push(int x) {
        if (this.stack.size() == 0) this.stack.offer(x);
        else {
            this.queue.offer(x);
            while (this.stack.size() != 0) this.queue.offer(this.stack.poll());
            Queue<Integer> temp = this.stack;
            this.stack = this.queue;
            this.queue = temp;
        }
    }
    
    public int pop() {
        return this.stack.poll();
    }
    
    public int top() {
        return this.stack.peek();
    }
    
    public boolean empty() {
        return this.stack.size() == 0;
    }
}