数据结构(三十三)
学习数据结构与算法过程中的心得体会以及知识点的整理,方便我自己查找,也希望可以和大家一起交流。
—— 包含min函数的栈 ——
1.题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
2.代码
c
typedef struct minst{
struct minst *next;
int value;
int min_num;
} MinStack;
/** initialize your data structure here. */
MinStack* minStackCreate() {
MinStack *min_top = (MinStack*)malloc(sizeof(MinStack));
min_top->next=NULL;
return min_top;
}
void minStackPush(MinStack* obj, int x) {
MinStack *min_stack = (MinStack*)malloc(sizeof(MinStack));
min_stack->value=x;
if(obj->next==NULL || x < obj->next->min_num)
min_stack->min_num=x;
else
min_stack->min_num=obj->next->min_num;
min_stack->next=obj->next;
obj->next=min_stack;
}
void minStackPop(MinStack* obj) {
if(obj->next!=NULL)
obj->next=obj->next->next;
}
int minStackTop(MinStack* obj) {
return obj->next->value;
}
int minStackMin(MinStack* obj) {
return obj->next->min_num;
}
void minStackFree(MinStack* obj) {
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 = minStackMin(obj);
* minStackFree(obj);
*/