3.4 Queue via Stacks

Using two stacks to implement queue.

class Queue {
public:
    stack<int> stkIn;
    stack<int> stkOut;
    // Push element x to the back of queue.
    void push(int x) {
        stkIn.push(x);
    }

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

    // Get the front element.
    int peek(void) {
        if(stkOut.empty()){
            while(stkIn.size()){
                stkOut.push(stkIn.top());
                stkIn.pop();
            }
        }
        return stkOut.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return (stkOut.empty() && stkIn.empty());
    }
};

你可能感兴趣的:(stack)