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

LeetCode "Implement Queue using Stacks"

时间:2015-07-07 07:03:55      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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

 

LeetCode "Implement Queue using Stacks"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4625852.html

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