程序员面试金典 3.4

Queue via Stacks:使用两个栈实现队列。

队列的特点是先进先出,栈的特点是先进后出,所以pop()操作应该和入栈顺序相反,这样第二个栈就派上用场了。在pop()时可以将元素全部导入第二个栈中,然后对第二个栈进行pop()操作,最后再将元素全部倒回去。这种方法虽然可行,但是来回倒腾元素会产生很多无意义的操作,所以可以采取较为懒惰的方法,让元素在第二个栈里先放着。

class MyQueue {
private:
    stack<int> sOldest, sNewest;
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        sNewest.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int tmp;
        if(sOldest.empty()){
            while(!sNewest.empty()){
                tmp = sNewest.top();
                sNewest.pop();
                sOldest.push(tmp);
            }
        }
        tmp = sOldest.top();
        sOldest.pop();
        return tmp;
    }
    
    /** Get the front element. */
    int peek() {
        int ret = pop();
        sOldest.push(ret);
        return ret;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return sOldest.empty() && sNewest.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

你可能感兴趣的:(《程序员面试金典》)