155. 最小栈
难度简单
设计一个支持 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
push(x)
—— 将元素 x 推入栈中。pop()
—— 删除栈顶的元素。top()
—— 获取栈顶元素。getMin()
—— 检索栈中的最小元素。
示例:
输入: ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] 输出: [null,null,null,null,-3,null,0,-2] 解释: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
提示:
pop
、top
和getMin
操作总是在 非空栈 上调用。
思路:该题是考察栈的基本操作。
1 typedef struct { 2 int *data; 3 int top; 4 int min; 5 } MinStack; 6 7 /** initialize your data structure here. */ 8 9 MinStack* minStackCreate() { 10 MinStack *obj; 11 obj=(MinStack*)malloc(sizeof(MinStack)); 12 if(obj!=NULL){ 13 obj->data=(int*)malloc(10000*sizeof(int)); 14 obj->top=-1; 15 return obj; 16 } 17 return NULL; 18 } 19 20 void minStackPush(MinStack* obj, int x) { 21 obj->data[++(obj->top)]=x; 22 } 23 24 void minStackPop(MinStack* obj) { 25 obj->top--; 26 } 27 28 int minStackTop(MinStack* obj) { 29 return obj->data[obj->top]; 30 } 31 32 int minStackGetMin(MinStack* obj) { 33 int i; 34 obj->min=obj->data[0]; 35 for(i=1;i<=obj->top;i++){ 36 if(obj->min>obj->data[i]){ 37 obj->min=obj->data[i]; 38 } 39 } 40 return obj->min; 41 } 42 43 void minStackFree(MinStack* obj) { 44 free(obj); 45 } 46 47 /** 48 * Your MinStack struct will be instantiated and called as such: 49 * MinStack* obj = minStackCreate(); 50 * minStackPush(obj, x); 51 52 * minStackPop(obj); 53 54 * int param_3 = minStackTop(obj); 55 56 * int param_4 = minStackGetMin(obj); 57 58 * minStackFree(obj); 59 */