llllmz

导航

232. 用栈实现队列

class MyQueue {
public:
    MyQueue()
    {
    }
    
    void push(int x) {
        s1.push(x);
    }
    
    int pop() {
        int ret;
        if(!empty()){
            if(!s2.empty()){
                ret = s2.top();
                s2.pop();
                return ret;
            }else{
                while(!s1.empty()){
                    int temp = s1.top();
                    s1.pop();
                    s2.push(temp);
                }
                ret = s2.top();
                s2.pop();
                return ret;
            } 
        }
        return -1;  
    }
    
    int peek() {
        if(s2.empty()){
            while(!s1.empty()){
                int temp = s1.top();
                s1.pop();
                s2.push(temp);
            }
        }
        return s2.top();
    }
    
    bool empty() {
        return s1.empty() && s2.empty();
    }
private:
    stack<int> s1;
    stack<int> s2;
};

posted on 2024-10-22 19:08  神奇的萝卜丝  阅读(2)  评论(0编辑  收藏  举报