其他分享
首页 > 其他分享> > LeetCode_155-Min Stack

LeetCode_155-Min Stack

作者:互联网

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

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

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

标签:Node,155,nullptr,LeetCode,pHead,nMinNum,pTmp,Stack,pNext
来源: https://blog.csdn.net/Yeir0/article/details/101451633