题目:

题解:


//单调栈 单调递减
typedef struct 
{
    //正常 stack
    int stack[10000];
    int stackTop;

    //辅助 stack
    int minStack[10000];
    int minStackTop;
} MinStack;


MinStack* minStackCreate() 
{
    MinStack* newStack      = (MinStack *) malloc(sizeof(MinStack));
    newStack->stackTop      = 0;
    newStack->minStackTop   = 0;
    return newStack;
}

void minStackPush(MinStack* obj, int val) 
{
    //先压如数据栈
    obj->stack[obj->stackTop++] = val;
    //当前值 小于等于 辅助栈顶值
    if(!obj->minStackTop || val <= obj->minStack[obj->minStackTop-1] )
    {
        obj->minStack[obj->minStackTop++] = val;
    }
    
}

void minStackPop(MinStack* obj)
{
    if( obj->minStack[obj->minStackTop-1]  == obj->stack[obj->stackTop-1] )
    {
        obj->minStackTop--;
    }
    obj->stackTop--;
}

int minStackTop(MinStack* obj) 
{
    return obj->stack[obj->stackTop-1]; 
}

int minStackGetMin(MinStack* obj) 
{
    return obj->minStack[obj->minStackTop-1]; 
}

void minStackFree(MinStack* obj) 
{
    free(obj);
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部