Leetcode Stack practice summary
#define STACK_INIT_SIZE 1000 //Stack初始大小
#define STACKINCREMENT 100 //空间耗尽时,的增量。
#define SElemType int //指定元素类型
typedef struct {
SElemType* base;
SElemType* top;
int stacksize;
} MinStack;
/** initialize your data structure here-> */
MinStack* minStackCreate() {
MinStack* S = (MinStack*)malloc(sizeof(MinStack));
if (!S)
return NULL;
S->base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S->base)
return NULL;
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 = (SElemType*)realloc(obj->base,(obj->stacksize + STACKINCREMENT)*sizeof(SElemType));
if(!obj->base)
return;
obj->top = obj->base + obj->stacksize;
obj->stacksize = obj->stacksize + STACKINCREMENT;
}
//////////END////////////////////////////
*(obj->top++) = x; //入栈
}
void minStackPop(MinStack* obj) {
////////////如果栈空///////
if(obj->top == obj->base)
return;
/////////////END/////////////
obj->top--; //出栈
}
int minStackTop(MinStack* obj) {
if(obj->top == obj->base)
return NULL;
return *(obj->top-1);
}
int minStackGetMin(MinStack* obj) {
SElemType* min;
min = obj->base;
for(SElemType* curr=obj->top; curr != obj->base; curr--){
if(*(curr-1) < *min)
min = curr-1;
}
return *min;
}
void minStackFree(MinStack* obj) {
if(obj){
if(obj->base)
free(obj->base);
free(obj);
}
}
Stack的基本操作。