【剑指offer】【栈】09.用两个栈实现队列

用两个栈实现队列

两个栈,st栈,cache缓存栈;
    1. 入队:直接压入st中;
    2. 出队 1)若cache为空:依次将st中的元素弹出并压入cache中;
            2)返回cache栈顶元素,cache栈顶出栈
    3. 获取栈顶元素:与出队类似,少一个pop
    4. 判空:cache和st同时为空,则为空
class MyQueue {
public:
    stack<int> st, cache;
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        st.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(st.empty() && cache.empty()) return -1;
        if(cache.empty())
        {
            while(!st.empty())
            {
                cache.push(st.top());
                st.pop();
            }
        }
        int res = cache.top();
        cache.pop();
        return res;
    }
    
    /** Get the front element. */
    int peek() {
        if(st.empty() && cache.empty()) return -1;
        if(cache.empty())
        {
            while(!st.empty())
            {
                cache.push(st.top());
                st.pop();
            }
        }
        int res = cache.top();
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return (st.empty() && cache.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();
 */

猜你喜欢

转载自www.cnblogs.com/Trevo/p/12590756.html