【leetcode】232. Implement Queue using Stacks

来源:互联网 发布:王牌特工知乎 编辑:程序博客网 时间:2024/06/05 02:35
@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());    }};

0 0
原创粉丝点击