Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Very similar as "Implement Stack using Queues".

class Queue 
{
    stack<int> _s0;
    stack<int> _s1;
    int _front;    

public:
    // Push element x to the back of queue.
    void push(int x) 
    {
        if(_s0.empty()) _front = x;
        _s0.push(x);    
    }

    // Removes the element from in front of queue.
    void pop(void) 
    {
        while(!_s0.empty())
        {
            _s1.push(_s0.top());
            _s0.pop();
        }
        _s1.pop();
        if(!_s1.empty())
        {
            _front = _s1.top();
            while(!_s1.empty())
            {
                _s0.push(_s1.top());
                _s1.pop();
            }
        }
    }

    // Get the front element.
    int peek(void) {
        return _front;
    }

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

 

posted on 2015-07-07 04:45  Tonix  阅读(177)  评论(0编辑  收藏  举报