其他分享
首页 > 其他分享> > LeetCode_232-Implement Queue using Stacks

LeetCode_232-Implement Queue using Stacks

作者:互联网

题意是使用栈实现队列;队列是先进先出,后进后出。

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        //intput
        m_bSwap = true;
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        if(!m_bSwap) {
            while(!m_soutput.empty()) {
                m_sintput.push(m_soutput.top());
                m_soutput.pop();
            }
            m_bSwap = true;
        }
        m_sintput.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(m_bSwap) {
            while(!m_sintput.empty()) {
                m_soutput.push(m_sintput.top());
                m_sintput.pop();
            }
            m_bSwap = false;
        }
        int nNum = m_soutput.top();
        m_soutput.pop();
        return nNum;
    }
    
    /** Get the front element. */
    int peek() {
        if(m_bSwap) {
            while(!m_sintput.empty()) {
                m_soutput.push(m_sintput.top());
                m_sintput.pop();
            }
            m_bSwap = false;
        }
        return m_soutput.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(m_sintput.empty() && m_soutput.empty()) {
            return true;
        }
        return false;
    }
 
protected:
    stack<int> m_sintput;
    stack<int> m_soutput;
    bool m_bSwap;
};

可关注公众号了解更多的面试技巧

标签:sintput,soutput,top,pop,Queue,empty,using,Stacks,bSwap
来源: https://www.cnblogs.com/yew0/p/11613918.html