What's the bug in this code? it get run time error in the test case.


  • 0
    R

    I use stackt to stimulate a stack, and a minindex to maintain the smallest elem's index in stack_t. But it get run time error. Anyone can help me to point where is the bug? Thanks!

    class MinStack {
    public:
        void push(int x) {
            index_of_stack++;
            if (index_of_stack == totle_size_of_stack) { // Full
                stack_t = (int*)realloc(stack_t, sizeof(int) * (totle_size_of_stack+1000));
                totle_size_of_stack = totle_size_of_stack + 1000;
            }
            stack_t[index_of_stack] = x;
            
            if (index_of_min_ == -1 || x < getMin())
                index_of_min_++;
            else 
                return;
            
            if (index_of_min_ == totle_size_of_min_) {
                min_index = (int*)realloc(min_index, sizeof(int) * (totle_size_of_min_+1000));
                totle_size_of_min_ = totle_size_of_min_ + 1000;
            }
            min_index[index_of_min_] = index_of_stack;
        }
    
        void pop() {
            if (index_of_stack == min_index[index_of_min_])
                index_of_min_--;
            index_of_stack--;
        }
    
        int top() {
            return stack_t[index_of_stack];
        }
    
        int getMin() {
            return stack_t[min_index[index_of_min_]];
        }
        
        int index_of_stack = -1;
        int index_of_min_  = -1;
        
        int totle_size_of_stack = 10;
        int totle_size_of_min_  = 10;
        
        int * stack_t   = (int *)malloc(sizeof(int) * 10);
        int * min_index = (int *)malloc(sizeof(int) * 10);
    };

Log in to reply
 

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