Share my C++ solution, created my own stack.


  • 0
    G

    class MinStack {
    private:
    class stackNode {
    public:
    int val;
    int min;
    stackNode* next;
    stackNode(int val) {
    this->val = val;
    next = NULL;
    }
    };
    stackNode* topNode;
    public:
    /** initialize your data structure here. */
    MinStack() {
    topNode = NULL;
    }

    void push(int x) {
        int minVal = topNode?min(topNode->min, x):x;
        stackNode* curr = new stackNode(x);
        curr->next = topNode;
        topNode = curr;
        topNode->min = minVal;
    }
    
    void pop() {
        stackNode* curr = topNode;
        topNode = curr->next;
        delete curr;
    }
    
    int top() {
        return topNode->val;
    }
    
    int getMin() {
        return topNode->min;
    }
    

    };


  • 0
    G
    class MinStack {
    private:
        class stackNode {
        public:
            int val;
            int min;
            stackNode* next;
            stackNode(int val) {
                this->val = val;
                next = NULL;
            }
        };
        stackNode* topNode;
    public:
        /** initialize your data structure here. */
        MinStack() {
            topNode = NULL;
        }
        
        void push(int x) {
            int minVal = topNode?min(topNode->min, x):x;
            stackNode* curr = new stackNode(x);
            curr->next = topNode;
            topNode = curr;
            topNode->min = minVal;
        }
        
        void pop() {
            stackNode* curr = topNode;
            topNode = curr->next;
            delete curr;
        }
        
        int top() {
            return topNode->val;
        }
        
        int getMin() {
            return topNode->min;
        }
    };
    

  • 0
    G

    Please discard the earlier post.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.