首页 > 其他 > 详细

LeetCode_232-Implement Queue using Stacks

时间:2019-09-30 19:56:41      阅读:75      评论:0      收藏:0      [点我收藏+]

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

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;
};

技术分享图片

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

LeetCode_232-Implement Queue using Stacks

原文:https://www.cnblogs.com/yew0/p/11613918.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!