首页 > 其他 > 详细

【leetcode】232. Implement Queue using Stacks

时间:2015-08-06 20:30:27      阅读:88      评论:0      收藏:0      [点我收藏+]
@requires_authorization
@author johnsondu
@create_time 2015.8.6 19:28
@url <a target=_blank href="https://leetcode.com/problems/implement-queue-using-stacks/">Implement Queue using Stacks</a>
/************************
 * @description: emumerate.
 * @time_complexity:  O(n)
 * @space_complexity: O(n)
 ************************/

class Queue {
public:
    stack<int> in;
    stack<int> out;
    // 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();
        else{
            while(!in.empty()){
                int val = in.top();
                out.push(val);
                in.pop();
            }
            out.pop();
        }
    }

    // Get the front element.
    int peek(void) {
        if(!out.empty()) return out.top();
        else{
            while(!in.empty()) {
                int val = in.top();
                in.pop();
                out.push(val);
            }
            return out.top();
        }
    }

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】232. Implement Queue using Stacks

原文:http://blog.csdn.net/zone_programming/article/details/47321633

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!