[Leetcode]-Min Stack

来源:互联网 发布:淘宝优惠券在哪里看 编辑:程序博客网 时间:2024/06/16 12:39

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);}
1 0