两个栈实现队列

ryluo 2020-06-22 21:30:09

请用栈实现一个队列,支持如下四种操作:

注意:

样例

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

分析:

class MyQueue {
public:
    /** Initialize your data structure here. */ 
    stack<int> s_in, s_out;
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {
        s_in.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (s_out.empty())
            while(s_in.size()){
                s_out.push(s_in.top());
                s_in.pop();
            }

        int res = s_out.top();
        s_out.pop();
        return res;

    }

    /** Get the front element. */
    int peek() {
        if (s_out.empty())
            while(s_in.size()){
                    s_out.push(s_in.top());
                    s_in.pop();
            }

        return s_out.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return s_in.empty() && s_out.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */