225. Implement Stack using Queues

单个队列可以完成,重点在push函数,每次push后计算queue中的长度,循环n-1次把当前头部的元素转移至尾部。两头操作用ArrayDeque

class MyStack {
    Queue<Integer> q;

    /** Initialize your data structure here. */
    public MyStack() {
        this.q = new ArrayDeque<>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        this.q.add(x);
        int size = this.q.size();
        for (int i = 0; i < size - 1; i++) {
            this.q.add(this.q.poll()); 
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return this.q.poll();
    }

    /** Get the top element. */
    public int top() {
        return this.q.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return this.q.isEmpty();
    }
}

results matching ""

    No results matching ""