Implement Queue using Stacks

用兩個棧來操作,t存儲隊列的逆序,每次加入新元素就倒序使用s


class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        stack<int> s;
        while(!t.empty()) {
            s.push(t.top());
            t.pop();
        }
        s.push(x);
        while(!s.empty()){
            t.push(s.top());
            s.pop();
        }
    }

    // Removes the element from in front of queue.
    void pop(void) {
        t.pop();
    }

    // Get the front element.
    int peek(void) {
        return t.top();
        
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return t.empty();
    }
    private:
    stack<int> t;
    
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章