码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode]-Min Stack

时间:2015-07-01 22:14:05      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
题目:实现一个栈,拥有pop,push,top,getmin操作。
结题思路:pop,push,top很基本的,getmin的意思必须在栈顶返回栈中最小的元素,那么很容易想到,既然必须在栈顶访问到整个栈中的最小元素,因为是栈所以不可能是存在遍历操作的,即使使用链表实现(原理上可以,但从栈的角度出发不能),因此在push的时候就必须将最小元素放在栈顶。那么这样就简单了,每次都比较新元素element和栈顶的元素data,将较小者放入栈顶。

struct node {
    int min;
    int data;
    struct node* next;
};

typedef struct {
    struct node *top;
} MinStack;

void minStackCreate(MinStack *stack, int maxSize) {
    stack->top = NULL;
}

void minStackPush(MinStack *stack, int element) {
    struct node* p = (struct node*)malloc(sizeof(struct node));
    p->data = element;
    if(stack->top == NULL)
        p->min = element;
    else
    {
        if(stack->top->min > element)
            p->min = element;
        else
            p->min = stack->top->min;
    }
    p->next = stack->top;
    stack->top = p;

}

void minStackPop(MinStack *stack) {
    struct node* p = NULL;
    p = stack->top;
    stack->top = p->next;
    free(p);
}

int minStackTop(MinStack *stack) {
    return stack->top->data;
}

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

void minStackDestroy(MinStack *stack) {
    while(stack->top != NULL)
        minStackPop(stack);
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode]-Min Stack

标签:leetcode

原文地址:http://blog.csdn.net/xiabodan/article/details/46715117

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!