标签:sizeof free ini 元素 支持 -- min() typedef ase
typedef struct { int *top; int *base; int statckSize; } MinStack; /** initialize your data structure here. */ MinStack* minStackCreate(int maxSize) { MinStack *stack = (MinStack*)malloc(sizeof(MinStack)); stack->base = (int*)malloc(maxSize*sizeof(int)); stack->top = stack->base; stack->statckSize = maxSize; return stack; } void minStackPush(MinStack* obj, int x) { if(obj->top - obj->base <= obj->statckSize) { *(obj->top) = x; obj->top++; } else { exit(1); } } void minStackPop(MinStack* obj) { if(obj->top != obj->base) { obj->top--; } else { exit(1); } } int minStackTop(MinStack* obj) { return *(obj->top); } int minStackGetMin(MinStack* obj) { int min; int *top = obj->top; int *base = obj->base; min = *top; while((top--) != base) { if(*top < min) min = *top; } return min; } void minStackFree(MinStack* obj) { free(obj->base); free(obj); }
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
标签:sizeof free ini 元素 支持 -- min() typedef ase
原文地址:https://www.cnblogs.com/xinfenglee/p/10050611.html