码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_155-Min Stack

时间:2019-09-30 19:57:52      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:了解   initial   oid   info   lse   while   void   inf   一个   

栈的实现,多加了一个最小值的获取

class MinStack {
public:
    struct Node {
        int nNum;
        int nMinNum;
        Node* pNext;
        Node() {
            pNext = nullptr;
        }
    };
    /** initialize your data structure here. */
    MinStack() {
        m_pHead = nullptr;
    }
 
    ~MinStack() {
        while(m_pHead != nullptr) {
            Node* pTmp = m_pHead;
            m_pHead = m_pHead->pNext;
            delete pTmp;
            pTmp = nullptr;
        }
    }
    
    void push(int x) {
        if(m_pHead == nullptr) {
            m_pHead = new Node;
            m_pHead->pNext = nullptr;
            m_pHead->nMinNum = x;
        }
        else {
            Node* pTmp = new Node;
            pTmp->nMinNum = m_pHead->nMinNum;
            pTmp->pNext = m_pHead;
            m_pHead = pTmp;
            if(m_pHead->nMinNum > x) {
                m_pHead->nMinNum = x;
            }
        }
        m_pHead->nNum = x;
    }
    
    void pop() {
        if(m_pHead != nullptr) {
            Node* pTmp = m_pHead;
            m_pHead = m_pHead->pNext;
            delete pTmp;
            pTmp = nullptr;
        }
    }
    
    int top() {
        if(m_pHead != nullptr) {
            return m_pHead->nNum;
        }
        return 0;
    }
    
    int getMin() {
        return m_pHead->nMinNum;
    }
    
protected:
    Node* m_pHead;
};

技术图片

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

LeetCode_155-Min Stack

标签:了解   initial   oid   info   lse   while   void   inf   一个   

原文地址:https://www.cnblogs.com/yew0/p/11613919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!