leetcode 232. Implement Queue using Stacks

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> r, b;
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        r.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (b.empty()) {
            int size = r.size();
            for (int i = 0; i < size; i++) {
                int t = r.top();
                b.push(t);
                r.pop();
            }
        }
        int ret = b.top();
        b.pop();
        return ret;
    }
    
    /** Get the front element. */
    int peek() {
        if (b.empty()) {
            int size = r.size();
            for (int i = 0; i < size; i++) {
                int t = r.top();
                b.push(t);
                r.pop();
            }
        }
        return b.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return r.empty() && b.empty();
    }
};

 

posted on 2018-02-06 13:12  willaty  阅读(81)  评论(0编辑  收藏  举报

导航