包含min函式的棧(劍指offer)---C語言

MID丶wan發表於2020-10-18

定義棧的資料結構,請在該型別中實現一個能夠得到棧的最小元素的 min 函式在該棧中,呼叫 min、push 及 pop 的時間複雜度都是 O(1);
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:

各函式的呼叫總次數不超過 20000 次
 typedef struct
 {    
	int top;    
	int min_top;    
	int *stack;    
	int *min_stack;
 } MinStack;
/** initialize your data structure here. */
MinStack* minStackCreate()
 {    
	 MinStack *obj = (MinStack*)malloc(sizeof(MinStack));    
 	 obj->stack = (int*)malloc(sizeof(int)*10000);    
	 obj->min_stack = (int*)malloc(sizeof(int)*10000);    
	 obj->top = -1;    
	 obj->min_top = -1;    
 	 return obj;
 }
void minStackPush(MinStack* obj, int x)
{   
	obj->stack[++obj->top] = x;   
	if(obj->min_top == -1)   
	{       
		obj->min_stack[++obj->min_top] = x;   
	}   
	else if(obj->min_stack[obj->min_top] >= x)   
	{      
		 obj->min_stack[++obj->min_top] = x;   
	 }
 }
void minStackPop(MinStack* obj)
{    
	if(obj->stack[obj->top] == obj->min_stack[obj->min_top])    
	{        
		obj->top--;        
		obj->min_top--;    
	}    
	else    
	{        
		obj->top--;    
	}
}
int minStackTop(MinStack* obj) 
{    
	return obj->stack[obj->top];
}
int minStackMin(MinStack* obj) 
{    
	return obj->min_stack[obj->min_top];
}
void minStackFree(MinStack* obj) 
{    
	free(obj->stack);    
	free(obj->min_stack);    
	free(obj);
}
/** * Your MinStack struct will be instantiated and called as such: * MinStack* obj = minStackCreate(); * minStackPush(obj, x);  * minStackPop(obj);  * int param_3 = minStackTop(obj);  * int param_4 = minStackMin(obj);  * minStackFree(obj);*/

相關文章