implementation by linkedlist, C++


  • 0
    H

    class MinStack {
    private:
    int min;
    struct Node
    {
    int data;
    Node* next;
    };
    struct Node* topNode;
    public:
    /** initialize your data structure here. */
    MinStack() {
    topNode = NULL;
    min = INT_MAX;
    }

    void push(int x) {
        struct Node* newNode = new struct Node; 
        newNode->data = x;
        newNode->next = topNode;
        topNode = newNode; 
        if(x < min) min = x; 
        
    }
    
    void pop() {
        struct Node* temp = topNode;
        topNode = topNode->next;
        if(temp->data == min)
        {
            struct Node* head = topNode;
            int nodemin = INT_MAX; 
            while(head != NULL)
            {
                if(head->data < nodemin) nodemin = head->data;
                head = head->next; 
            }
            min = nodemin; 
        }
        delete(temp); 
        
    }
    
    int top() {
      if(topNode == NULL) return NULL;
      else return topNode->data; 
    }
    
    int getMin() {
        
    return min; 
    }
    

    };

    /**

    • Your MinStack object will be instantiated and called as such:
    • MinStack obj = new MinStack();
    • obj.push(x);
    • obj.pop();
    • int param_3 = obj.top();
    • int param_4 = obj.getMin();
      */

Log in to reply
 

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