设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
typedef struct node { int num; struct node *next; }Node; typedef struct stack { struct node *top; struct node *min; } MinStack; /** initialize your data structure here. */ MinStack* minStackCreate() { MinStack *new = malloc(sizeof(MinStack)); new->top = NULL; new->min = NULL; return new; } void minStackPush(MinStack* obj, int x) { struct node *newnode = malloc(sizeof(struct node)); newnode->num = x; newnode->next = obj->top; obj->top = newnode; if (!obj->min) { obj->min = newnode; } else { if (newnode->num < obj->min->num) { obj->min = newnode; } } } void minStackPop(MinStack* obj) { struct node *popnode = obj->top; struct node *minnode; struct node *tmp; if (popnode) { if (obj->min == popnode) { tmp = popnode->next; minnode = tmp; while(tmp && tmp->next) { tmp = tmp->next; if (tmp->num < minnode->num) minnode = tmp; } obj->min = minnode; } obj->top = popnode->next; free(popnode); popnode = NULL; } } int minStackTop(MinStack* obj) { return obj->top->num; } int minStackGetMin(MinStack* obj) { return obj->min->num; } void minStackFree(MinStack* obj) { struct node *tmp = obj->top; while(tmp != NULL) { obj->top = tmp->next; free(tmp); tmp = obj->top; } free(obj); obj = NULL; }