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的意思必须在栈顶返回栈中最小的元素。那么非常easy想到。既然必须在栈顶訪问到整个栈中的最小元素,由于是栈所以不可能是存在遍历操作的,即使使用链表实现(原理上能够,但从栈的角度出发不能)。因此在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);
}