用栈实现队列

class Queue {
private:
    stack<int> in;
    stack<int> out;
    
    void reverseStackToOut()
    {
        auto size = in.size();
        for (size_t i = 0; i < size; ++i){
            out.push(in.top());
            in.pop();
        }
    }
public:
    // Push element x to the back of queue.
    void push(int x) {
        in.push(x);
    }
    
    // Removes the element from in front of queue.
    void pop(void) {
        if (!out.empty()){
            out.pop();
            return;
        }
        
        if (in.empty()){
            return;
        }
        else{
            reverseStackToOut();
            out.pop();
        }
    }
    
    // Get the front element.
    int peek(void) {
        if (!out.empty()){
            return out.top();
        }
        
        if (in.empty()){
            return 0;
        }
        else{
            reverseStackToOut();
            return out.top();
        }
        
    }
    
    // Return whether the queue is empty.
    bool empty(void) {
        if (in.empty() && out.empty()){
            return true;
        }
        
        return false;
    }
};
原文地址:https://www.cnblogs.com/wuOverflow/p/4700624.html