用栈实现队列

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;
    }
};

 

posted @ 2015-08-03 22:28  wu_overflow  阅读(182)  评论(0编辑  收藏  举报