leetcode- face questions stack 30 to achieve O (1) The function min

Dp idea is to use dynamic programming, beginning just want to keep a min variable minimum stack structure inside, constantly updated constantly Push, but at the minimum station pop, pop unable to determine whether the value is not minimal. Thinking, only one variable is certainly not a record of all minimum state, engage in at least one array.
Therefore, the minimum stack structure which has a minimum memory access stack to the minimum, the minimum value when the value push (the stack memory to the array) is also smaller than the current, we will push the stack into the minimum value, when when the minimum value is greater than the current push, we will copy the previous minimum push to the stack.
Honestly, written in C leetcode for me that less code is really a form of exercise, and practice the realization of chain stack, and an array stack. For dynamic programming the same time also to deepen their understanding.
On the code:

#define MAX_VALUES 20001

typedef struct StackNode{
    int data;
    struct StackNode* next;
}StackNode,*MinStackPtr;

typedef struct {
    int min_stack[MAX_VALUES];
    int min_stack_top;
    int count;
    MinStackPtr top;
} MinStack;

/** initialize your data structure here. */

MinStack* minStackCreate() {
    MinStack* p=malloc(sizeof(MinStack));
    for(int i=0;i<MAX_VALUES;i++){
        p->min_stack[i]=INT_MAX;
    }
    p->min_stack_top=0;
    p->count=0;
    p->top=NULL;
    return p;
}

void minStackPush(MinStack* obj, int x) {
    MinStackPtr s=malloc(sizeof(StackNode));
    s->data=x;
    s->next=obj->top;
    obj->top=s;
    obj->count++;
    if(x <= obj->min_stack[obj->min_stack_top]){
        obj->min_stack[++obj->min_stack_top]=x;
    }
    else{
        obj->min_stack[obj->min_stack_top+1]=obj->min_stack[obj->min_stack_top];
        obj->min_stack_top++;
    }
}

void minStackPop(MinStack* obj) {
    obj->min_stack_top--;
    if(obj->count==0)
        return;
    MinStackPtr s=obj->top;
    obj->top=obj->top->next;
    free(s);
    obj->count--;
}

int minStackTop(MinStack* obj) {
    return obj->top->data;
}

int minStackMin(MinStack* obj) {
    return obj->min_stack[obj->min_stack_top];
}

void minStackFree(MinStack* obj) {
    MinStackPtr s=obj->top;
    MinStackPtr temp;
    while(s){
        temp=s;
        s=s->next;
        free(temp);
    }
    obj->top=NULL;
    obj->count=0;
}

/**
 * Your MinStack struct will be instantiated and called as such:
 * MinStack* obj = minStackCreate();
 * minStackPush(obj, x);
 
 * minStackPop(obj);
 
 * int param_3 = minStackTop(obj);
 
 * int param_4 = minStackMin(obj);
 
 * minStackFree(obj);
*/
Published 19 original articles · won praise 1 · views 3125

Guess you like

Origin blog.csdn.net/qq_41603639/article/details/104890461