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);
*/
相关推荐
linsa_pursuer28 分钟前
快乐数算法
算法·leetcode·职场和发展
XuanRanDev34 分钟前
【每日一题】LeetCode - 三数之和
数据结构·算法·leetcode·1024程序员节
代码猪猪傻瓜coding35 分钟前
力扣1 两数之和
数据结构·算法·leetcode
南宫生2 小时前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
passer__jw7673 小时前
【LeetCode】【算法】283. 移动零
数据结构·算法·leetcode
星沁城5 小时前
240. 搜索二维矩阵 II
java·线性代数·算法·leetcode·矩阵
一直学习永不止步5 小时前
LeetCode题练习与总结:赎金信--383
java·数据结构·算法·leetcode·字符串·哈希表·计数
劲夫学编程8 小时前
leetcode:杨辉三角
算法·leetcode·职场和发展
师太,答应老衲吧12 小时前
SQL实战训练之,力扣:2020. 无流量的帐户数(递归)
数据库·sql·leetcode
passer__jw76720 小时前
【LeetCode】【算法】208. 实现 Trie (前缀树)
算法·leetcode