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

【leetcode】232. Implement Queue using Stacks

时间:2015-08-06 20:31:57      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   stack   queue   

@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

标签:leetcode   algorithm   stack   queue   

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

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