下面直接上代码:
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 20
typedef struct {
int *top;
int *base;
int stackSize;
} MinStack;
MinStack* minStackCreate() {
MinStack *s = malloc (sizeof(MinStack));
if (!s) return NULL;
s->base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
s->top=s->base;
s->stackSize=STACK_INIT_SIZE;
return s;
}
void minStackPush(MinStack* obj, int x) {
if(obj->top-obj->base==obj->stackSize)
{
obj->base=(int *)realloc(obj->base,(obj->stackSize+STACKINCREMENT)*sizeof(int));
obj->top=obj->base+obj->stackSize;
obj->stackSize=obj->stackSize+STACKINCREMENT;
}
*(obj->top)=x;
obj->top++;
}
void minStackPop(MinStack* obj) {
if(obj->top==obj->base)
return;
obj->top--;
}
int minStackTop(MinStack* obj) {
if(obj->top==obj->base)
return -1;
int x = *(obj->top-1);
return x;
}
int minStackGetMin(MinStack* obj) {
int min=*(obj->base),x=*(obj->top-1),size=obj->top-obj->base;
while(obj->top!=obj->base)
{
obj->top--;
x=*(obj->top);
if(min>x)
min=x;
}
obj->top=obj->top+size;
return min;
}
void minStackFree(MinStack* obj) {
free(obj);
}