【leetcode】Min Stack

Problem

這裏寫圖片描述

Code

typedef struct {
    int *value;     //Array to put elements
    int minIndex;   //The minimum's index
    unsigned int length;    //The elements' number
    unsigned int size;      //The capacity
} MinStack;

void minStackCreate(MinStack *stack, int maxSize) {
    stack->size = maxSize;
    stack->length = 0;
    stack->value = (int*)calloc(maxSize,sizeof(int));
    stack->minIndex = 0;
}

void minStackPush(MinStack *stack, int element) {
    if(stack->length == stack->size)
        return;
    stack->value[stack->length++] = element;
    stack->minIndex = stack->value[stack->minIndex] > element ? stack->length-1 : stack->minIndex;
}

void minStackPop(MinStack *stack) {
    if(!stack->length)
        return;
    --stack->length;
    /* If the deleted element is the minimun */
    if(stack->length == stack->minIndex){
        stack->minIndex = 0;
        /* Find the minimun's index */
        for(int i=1;i<stack->length;++i)
            stack->minIndex = stack->value[stack->minIndex] > stack->value[i] ? i : stack->minIndex;
    }
}

int minStackTop(MinStack *stack) {
    if(!stack->length)
        return 0;
    return stack->value[stack->length-1];
}

int minStackGetMin(MinStack *stack) {
    if(!stack->length)
        return 0;
    return stack->value[stack->minIndex];
}

void minStackDestroy(MinStack *stack) {
    free(stack->value);
}

Comments

This is a very simple problem,but it is useful in the reality.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章