2024/4/2—力扣—栈的最小值

代码实现:

cpp 复制代码
typedef struct node {
    int val;
    struct node *next;
} Node;

typedef struct {
    struct node *top;
    int min;
} MinStack;

/** initialize your data structure here. */

MinStack* minStackCreate() {
    MinStack *obj = malloc(sizeof(*obj));
    obj->top = NULL;
    obj->min = INT_MAX;
    return obj;
}

void minStackPush(MinStack *obj, int x) {
    Node *p = malloc(sizeof(*p));
    p->val = x;
    p->next = NULL;
    obj->min = obj->min > x ? x : obj->min;
    if (obj->top == NULL) {
        obj->top = p;
    } else {
        p->next = obj->top;
        obj->top = p;
    }
}

void minStackPop(MinStack *obj) {
    Node *pc = obj->top;
    obj->top = obj->top->next;
    if (obj->top == NULL) {
        obj->min = INT_MAX;
    } else if (pc->val == obj->min) {
        Node *p = obj->top;
        int fmin = p->val;
        while (p) {
            if (fmin > p->val) {
                fmin = p->val;
            }
            p = p->next;
        }
        obj->min = fmin; 
    }
    pc->next = NULL;
    free(pc);
}

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

int minStackGetMin(MinStack *obj) {
    return obj->min;
}

void minStackFree(MinStack *obj) {
    Node *pc = obj->top;
    while (pc) {
        obj->top = obj->top->next;
        pc->next = NULL;
        free(pc);
        pc = obj->top;
    }
    free(obj);
}

/**
 * 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 = minStackGetMin(obj);
 
 * minStackFree(obj);
*/
相关推荐
烦躁的大鼻嘎4 分钟前
模拟算法实例讲解:从理论到实践的编程之旅
数据结构·c++·算法·leetcode
祁思妙想40 分钟前
10.《滑动窗口篇》---②长度最小的子数组(中等)
leetcode·哈希算法
alphaTao2 小时前
LeetCode 每日一题 2024/11/18-2024/11/24
算法·leetcode
kitesxian2 小时前
Leetcode448. 找到所有数组中消失的数字(HOT100)+Leetcode139. 单词拆分(HOT100)
数据结构·算法·leetcode
jiao_mrswang4 小时前
leetcode-18-四数之和
算法·leetcode·职场和发展
王燕龙(大卫)4 小时前
leetcode 数组中第k个最大元素
算法·leetcode
Swift社区13 小时前
LeetCode - #139 单词拆分
算法·leetcode·职场和发展
Dong雨14 小时前
力扣hot100-->栈/单调栈
算法·leetcode·职场和发展
trueEve16 小时前
SQL,力扣题目1369,获取最近第二次的活动
算法·leetcode·职场和发展
九圣残炎17 小时前
【从零开始的LeetCode-算法】3354. 使数组元素等于零
java·算法·leetcode