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);
*/
相关推荐
爱爬山的老虎33 分钟前
【面试经典150题】LeetCode121·买卖股票最佳时机
数据结构·算法·leetcode·面试·职场和发展
雾月551 小时前
LeetCode 914 卡牌分组
java·开发语言·算法·leetcode·职场和发展
想跑步的小弱鸡1 小时前
Leetcode hot 100(day 4)
算法·leetcode·职场和发展
Fantasydg1 小时前
DAY 35 leetcode 202--哈希表.快乐数
算法·leetcode·散列表
jyyyx的算法博客1 小时前
Leetcode 2337 -- 双指针 | 脑筋急转弯
算法·leetcode
ゞ 正在缓冲99%…1 小时前
leetcode76.最小覆盖子串
java·算法·leetcode·字符串·双指针·滑动窗口
惊鸿.Jh2 小时前
【滑动窗口】3254. 长度为 K 的子数组的能量值 I
数据结构·算法·leetcode
想跑步的小弱鸡9 小时前
Leetcode hot 100(day 3)
算法·leetcode·职场和发展
SsummerC15 小时前
【leetcode100】每日温度
数据结构·python·leetcode
Swift社区16 小时前
Swift LeetCode 246 题解:中心对称数(Strobogrammatic Number)
开发语言·leetcode·swift