面试题 03.04. 化栈为队

面试题 03.04. 化栈为队

思路:用2个栈,元素经过2个栈之后,顺序就和队列顺序一样了

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(s2.size()==0){
            while(s1.size()){
                s2.push(s1.top());
                s1.pop();
            }
        }
        int res = s2.top();
        s2.pop();
        return res;
    }
    
    /** Get the front element. */
    int peek() {
        if(s2.size()==0){
            while(s1.size()){
                s2.push(s1.top());
                s1.pop();
            }
        }
        int res = s2.top();
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.size()==0 && s2.size()==0;
    }
private:
    stack<int> s1,s2;
};
发布了248 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38603360/article/details/105159113