最小栈解决O(1)时间复杂度内最小值的查找
题目描述
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
要求在常数时间内找到栈中最小值为重点要求。即时间复杂度为O(1)。
题目作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetb...
题目来源:力扣(LeetCode)
题解作者:WildDuck
题目分析
代码实现
#define Elemtype int
struct MinStack
{
Elemtype val;
struct MinStack* next;
struct MinStack* Min_stack;
};
typedef struct MinStack MinStack;
typedef struct MinStack* MinStack_pointer;
/** initialize your data structure here. */
//使用链式存储结构实现栈 严格限制从头部开始操作
MinStack* minStackCreate()
{
//头部指针作为栈顶位置,标识并控制整个栈
MinStack_pointer head = (MinStack_pointer)malloc(sizeof(struct MinStack));
head->val = -1;
head->next = NULL;
head->Min_stack = NULL;
return head;
}
void minStackPush(MinStack* obj, int val)
{
//根据链式结构实现栈,栈的push必须用头插法实现
//此类实现方式的好处高效使用内存空间、不限定栈大小情况下不会溢出
MinStack_pointer new_elem = (MinStack_pointer)malloc(sizeof(struct MinStack));
obj -> val = obj -> val + 1;
new_elem -> val = val;
new_elem -> next = obj -> next;
new_elem -> Min_stack = NULL;
obj ->next = new_elem;
if(obj -> Min_stack == NULL)
{
obj -> Min_stack = new_elem;
}
else if(obj -> Min_stack != NULL && (obj -> Min_stack -> val) > val)
{
obj -> Min_stack = new_elem;
}
new_elem -> Min_stack = obj->Min_stack;
}
void minStackPop(MinStack* obj)
{
//根据链式结构实现栈,栈的push必须用头删法实现
MinStack_pointer temp_elem = obj->next;
if(obj->Min_stack == obj->next)
{
if(obj->val > 0)
{
obj -> Min_stack = ((obj->next)->next)->Min_stack;
}
else if(obj->val == 0)
{
obj -> Min_stack = NULL;
}
}
obj -> next = obj->next->next;
obj -> val = obj -> val -1;
free(temp_elem);
}
int minStackTop(MinStack* obj)
{
return obj->next->val;
}
int minStackGetMin(MinStack* obj)
{
return obj->Min_stack->val;
}
/**
* Your MinStack struct will be instantiated and called as such:
* MinStack* obj = minStackCreate();
* minStackPush(obj, val);
* minStackPop(obj);
* int param_3 = minStackTop(obj);
* int param_4 = minStackGetMin(obj);
*/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。