题目
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() ——检索栈中的最小元素。
示例:
输入:
[“MinStack”,“push”,“push”,“push”,“getMin”,“pop”,“top”,“getMin”]
[[],[-2],[0],[-3],[],[],[],[]]输出:
[null,null,null,null,-3,null,0,-2]解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:
pop、top 和 getMin 操作总是在 非空栈 上调用。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
用C实现了链式栈,具体实现可看 数据结构(C语言)链式栈
法一:觉得自己写的漏洞很多,但是编译通过了
法二是法一的优化
typedef struct Stack
{
int data;
struct Stack* next;
} MinStack;
MinStack* minStackCreate()
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
p->next = NULL;
return p;
}
void minStackPush(MinStack* obj, int val)
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
p->data = val;
p->next = obj->next;
obj->next = p;
}
void minStackPop(MinStack* obj)
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
p = obj->next;
obj->next = p->next;
}
int minStackTop(MinStack* obj)
{
return obj->next->data;
}
int minStackGetMin(MinStack* obj)
{
int min = obj->next->data;
for (MinStack* p = obj->next; p != NULL; p = p->next)
{
min = fmin(min, p->data);
}
return min;
}
void minStackFree(MinStack* obj)
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
while (obj->next != NULL)
{
p = obj->next;
obj->next = p->next;
free(p);
}
}
法二:优化了GetMin ,在结构体中增加了 min,当第一个节点push时,min就那等于当前节点的date;之后,min = fmin( obj -> next -> min , p->data )
typedef struct Stack
{
int data;
int min;
struct Stack* next;
} MinStack;
MinStack* minStackCreate()
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
p->next = NULL;
return p;
}
void minStackPush(MinStack* obj, int val)
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
p->data = val;
if(obj->next==NULL)p->min=p->data;
else p->min=fmin(obj->next->min,p->data);
p->next = obj->next;
obj->next = p;
}
void minStackPop(MinStack* obj)
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
p = obj->next;
obj->next = p->next;
}
int minStackTop(MinStack* obj)
{
return obj->next->data;
}
int minStackGetMin(MinStack* obj)
{
return obj->next->min;
}
void minStackFree(MinStack* obj)
{
MinStack* p = (MinStack*)malloc(sizeof(MinStack));
while(obj->next!=NULL)
{
p = obj->next;
obj->next=p->next;
free(p);
}
}