/*
设计一个支持 push,pop,getmin 等操作
并且可以在 O(1) 时间内检索出最小元素的堆栈A。
验证案例:1)创建栈,大小为10,压入元素 3,2,2,1,通过调用getmin打印最小值
2) 弹出1个元素后 通过调用getmin打印最小值
3) 再弹出1个元素后通过调用getmin打印最小值
4) 再次压入元素4,通过调用getmin打印最小值
*/
#include <stdio.h>
#include <malloc.h>
#define MaxSize 10
typedef int ElementType;
typedef struct {
ElementType dataA[MaxSize];
ElementType dataB[MaxSize];
int top1;
int top2;
} SqStack;
//新建最小栈
SqStack * CreateStack( ) {
SqStack* s = (SqStack*)malloc(sizeof(SqStack));
s->top1 = -1;
s->top2 = -1;
return s;
}
//压栈操作
void Push( SqStack *s, ElementType x ) {
if (s->top1 == MaxSize - 1) {
printf("栈满\n");
return;
}
if (s->top1 == -1) {
s->dataA[++s->top1] = x;
s->dataB[++s->top2] = x;
} else {
s->dataA[++s->top1] = x;
if (x < s->dataB[s->top2]) {
s->dataB[++s->top2] = x;
} else {
s->top2++;
s->dataB[s->top2] = s->dataB[s->top2 - 1];
}
}
}
//出栈操作
ElementType Pop( SqStack *s) {
if (s->top1 == -1)
printf("栈空!\n");
else {
s->top1--;
s->top2--;
}
return s->dataA[s->top1+1];
}
int GetMin( SqStack *s) {
return s->dataB[s->top2];
}
int main() {
/*-------------1)创建栈,大小为10,压入元素 3,2,2,1通过调用getmin打印最小值----------------*/
SqStack * s = CreateStack();
Push(s, 3);
Push(s, 2);
Push(s, 2);
Push(s, 1);
printf("第一次打印最小值为:%d\n", GetMin(s));
/*--------------2) 弹出1个元素后 通过调用getmin打印最小值---------------*/
Pop(s);
printf("第二次打印最小值为:%d\n", GetMin(s));
/*--------------3) 再弹出1个元素后通过调用getmin打印最小值---------------*/
Pop(s);
printf("第三次打印最小值为:%d\n", GetMin(s));
/*--------------4) 再次压入元素4,通过调用getmin打印最小值---------------*/
Push(s, 4);
printf("第四次打印最小值为:%d\n", GetMin(s));
}