Implement Stack using queue

Queue 是先進先出,像排隊一樣

Stack 是先進後出,這題要用 Queue 實作出 stack

考點在於 top 時要怎樣取出最新的一個?

因為如果是用 queue 實作,那取出的會是最先加入的,而不是 stack 要的最後加入的

反過來想,在加入元素時,是不是就可以讓順序反過來?

我加入一個元素,就把元素調整到跟 stack 一樣的順序,那 top, pop 拿到的就會是對的值

class MyStack {

    private Queue<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }

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

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

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

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

push 那邊每加入一個元素後,就調整順序,

push 時間複雜度為 O(n)

results matching ""

    No results matching ""