• 最小栈问题


    设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

    • push(x) -- 将元素 x 推入栈中。
    • pop() -- 删除栈顶的元素。
    • top() -- 获取栈顶元素。
    • getMin() -- 检索栈中的最小元素。

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.getMin();   --> 返回 -2.

    typedef struct node {
        int num;
        struct node *next;
    }Node;
    
    typedef struct stack {
        struct node *top;
        struct node *min;
    } MinStack;
    
    /** initialize your data structure here. */
    
    MinStack* minStackCreate() {
        MinStack *new = malloc(sizeof(MinStack));
        new->top = NULL;
        new->min = NULL;
        return new;
    }
    
    void minStackPush(MinStack* obj, int x) {
        struct node *newnode = malloc(sizeof(struct node));
        newnode->num = x;
        
        newnode->next = obj->top;
        obj->top = newnode;
        
        if (!obj->min) {
            obj->min = newnode;
        }
        else {
            if (newnode->num < obj->min->num) {
                obj->min = newnode;
            }
        }        
    }
    
    void minStackPop(MinStack* obj) {
        struct node *popnode = obj->top;
        struct node *minnode;
        struct node *tmp;
        if (popnode) {
            if (obj->min == popnode) {
                tmp = popnode->next;
                minnode = tmp;
                while(tmp && tmp->next) {
                    tmp = tmp->next;
                    if (tmp->num < minnode->num)
                        minnode = tmp;
                }
                obj->min = minnode;
            }
    
            obj->top = popnode->next;
            free(popnode);
            popnode = NULL;
        }
        
        
    }
    
    int minStackTop(MinStack* obj) {
        return obj->top->num;
    }
    
    int minStackGetMin(MinStack* obj) {
        return obj->min->num;
    }
    
    void minStackFree(MinStack* obj) {
        struct node *tmp = obj->top;
        
        while(tmp != NULL) {
            obj->top = tmp->next;
            free(tmp);
            tmp = obj->top;
        }
        
        free(obj);
        obj = NULL;
    }
  • 相关阅读:
    时尚生活小秘方[转载]
    武侠片上的99个公式镜头
    SQL语句优化技术分析
    LoadRunner监视的性能计数器
    圣诞收到最搞笑的短信两则
    loadrunner 运行状态描述
    ORACLE 常用脚本[转载]
    关于内存泄漏检测问题,和大家一起分享
    小笑话
    [转贴] ++ 一个北大女孩给男友的道歉信(爆笑!!!)相当经典
  • 原文地址:https://www.cnblogs.com/xingmuxin/p/11271645.html
Copyright © 2020-2023  润新知