-
实例要求:
-
设计一个支持
入栈、出栈、取栈顶元素等操作
,并能在常数时间内检索到最小元素的栈
; -
实现
MinStack 类
: -
MinStack* minStackCreate()
初始化堆栈对象,即建栈
; -
void minStackPush(MinStack* obj, int val)
将元素val推入堆栈,即入栈
; -
void minStackPop(MinStack* obj)
删除堆栈顶部的元素,即出栈
; -
int minStackTop(MinStack* obj)
获取堆栈顶部的元素,即取栈顶元素
; -
int minStackGetMin(MinStack* obj)
获取堆栈中的最小元素,即取最小元素
; -
void minStackFree(MinStack* obj)
即销毁栈
; -
相关案例:
-
实例分析:
-
1、采用
单向链表的数据结构
; -
2、为了
提高程序的运算效率
,应采用头插法和头删法
; -
3、
头节点obj
始终指向NULL,头节点的next节点
作为栈顶节点top节点
; -
4、每个节点
存放当前最小栈的数值val
和当前最小栈的最小值min
; -
示例代码:
typedef struct Stack{
int val;
int min;
struct Stack *next;
} MinStack;
MinStack* minStackCreate() {
MinStack *minStack = (MinStack *)malloc(sizeof(MinStack));
if(minStack == NULL)
{
printf("内存分配失败\n");
}
minStack->next = NULL;
// minStack->val = 0;
// minStack->min = 0;
return minStack;
}
void minStackPush(MinStack* obj, int val) {
MinStack *new = (MinStack *)malloc(sizeof(MinStack));
new->val = val;
if(obj->next == NULL)
{
new->min = val;
}
else
{
new->min = ((new->val > obj->next->min) ? obj->next->min : new->val);
}
//头插
new->next = obj->next;
obj->next = new;
}
void minStackPop(MinStack* obj) {
//头删
MinStack *old = obj->next;
obj->next = old->next;
free(old);
old = NULL;
}
int minStackTop(MinStack* obj) {
return obj->next->val;
}
int minStackGetMin(MinStack* obj) {
return obj->next->min;
}
void minStackFree(MinStack* obj) {
//先清空栈
MinStack *temp = NULL;
while(obj->next != NULL)
{
temp = obj->next;
obj->next = temp->next;
free(temp);
temp = NULL;
}
//再销毁栈
free(obj);
obj = NULL;
}
/**
* 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);
* minStackFree(obj);
*/
- 运行结果: