Run time error in minstack


  • 0
    L

    Leetcode is giving me a runtime error for input push(-3), getmin. But, when I run the code locally, it works fine. What am I doing wrong?

    typedef struct MinStack{
        int value;
        struct  MinStack* below;
    } MinStack;
    
    MinStack* min = NULL;
    int Max_Size = 0;
    int size = 0;
    
    void minStackCreate(MinStack *stack, int maxSize) {
        Max_Size = maxSize;
        size = 0;
    }
    
    void minStackPush(MinStack *stack,int element) {
        if(stack == NULL){
            return;
        }
        if(size >= Max_Size){
            return;
        }
        if(stack == NULL){
        	printf("here\n");
            stack = malloc(sizeof(MinStack));
            if(stack == NULL){
                printf("Malloc failed\n");
                exit(0);
            }
            min = malloc(sizeof(MinStack));
            if(min == NULL){
                printf("Malloc failed\n");
                exit(0);
            }
            stack -> value = element;
            min -> value = element;
            stack -> below = NULL;
            min -> below = NULL;
        }
        else {
            MinStack *temp = malloc(sizeof(MinStack));
            if(temp == NULL){
                printf("Malloc Failed\n");
                exit(0);
            }
            temp -> below = stack;
            stack = temp;
            /*Adjust the min stack*/
            temp = malloc(sizeof(MinStack));
            if(temp == NULL){
                printf("Malloc failed\n");
                exit(0);
            }
            printf("current minimum is %d and element is %d\n",min -> value, element);
            if(min -> value < element){
                temp -> value = min -> value;
            }
            else {
                temp -> value = element;
            }
            temp -> below = min;
            min = temp;
        }
        size++;
    }
    
    void minStackPop(MinStack *stac) {
        MinStack* temp = stac;
        stack = stac -> below;
        free(temp);
        temp = min;
        min = min -> below;
        free(temp);
    }
    
    int minStackTop(MinStack *stack) {
        return stack -> value;
    }
    
    int minStackGetMin(MinStack *stack) {
    	if(min == NULL){
    		return -9999999;
    	}
        return min -> value;
    }
    
    void minStackDestroy(MinStack *stack) {
        MinStack* rover = min;
        MinStack* temp = NULL;
        while(rover != NULL){
            temp = rover -> below;
            free(rover);
            rover = temp;
        }
        rover = stack;
        while(rover != NULL){
            temp = rover -> below;
            free(rover);
            rover = temp;
        }
    }

Log in to reply
 

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