1. 程式人生 > >Leetcode225 用佇列實現棧

Leetcode225 用佇列實現棧

【方法一】

用一個輔助佇列,每當有元素push進“棧”,則需要把佇列的front位置給它空出來,方便後面直接pop()和top(),因此我們可以做兩次搬家操作,來獲得一個新的佇列:

class MyStack {
private:
    queue<int> q;
    queue<int> tmp;
public:
    
    
    /** Push element x onto stack. */
    void push(int x) {
        while(!q.empty())
        {
            tmp.push(q.front());
            q.pop();
        }
        q.push(x);
        while(!tmp.empty())
        {
            q.push(tmp.front());
            tmp.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res = q.front();
        q.pop();
        return res;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

【方法二】那麼有沒有複雜度更低的方法,比如一次直接到位的辦法呢?想想其實沒有必要用那個輔助佇列,在每次push()操作時,我們直接從佇列頭開始,把每一個元素複製到隊尾,然後刪除隊頭的這個元素,這樣push進來的新元素就到了front的位置:

 

class MyStack {
private:
    queue<int> q;
public:
    
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for(int i=0;i<q.size()-1;++i){
            q.push(q.front());
            q.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res = q.front();
        q.pop();
        return res;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};