代码实现:
typedef struct node {int val;struct node *next; } Node;typedef struct {struct node *top;int min; } MinStack;/** initialize your data structure here. */MinStack* minStackCreate() {MinStack *obj = malloc(sizeof(*obj));obj->top = NULL;obj->min = INT_MAX;return obj; }void minStackPush(MinStack *obj, int x) {Node *p = malloc(sizeof(*p));p->val = x;p->next = NULL;obj->min = obj->min > x ? x : obj->min;if (obj->top == NULL) {obj->top = p;} else {p->next = obj->top;obj->top = p;} }void minStackPop(MinStack *obj) {Node *pc = obj->top;obj->top = obj->top->next;if (obj->top == NULL) {obj->min = INT_MAX;} else if (pc->val == obj->min) {Node *p = obj->top;int fmin = p->val;while (p) {if (fmin > p->val) {fmin = p->val;}p = p->next;}obj->min = fmin; }pc->next = NULL;free(pc); }int minStackTop(MinStack *obj) {return obj->top->val; }int minStackGetMin(MinStack *obj) {return obj->min; }void minStackFree(MinStack *obj) {Node *pc = obj->top;while (pc) {obj->top = obj->top->next;pc->next = NULL;free(pc);pc = obj->top;}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 = minStackGetMin(obj);* minStackFree(obj); */