码迷,mamicode.com
首页 > 其他好文 > 详细

用栈实现队列

时间:2015-08-04 00:08:11      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

 

用栈实现队列

标签:

原文地址:http://www.cnblogs.com/wuOverflow/p/4700624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!