这个题官方解比较巧妙
class Solution { public: stack<int> data,minData; void push(int value) { data.push(value); if(minData.empty()){ minData.push(value); }else{ if(value < minData.top()){ minData.push(value); }else{ minData.push(minData.top()); } } } void pop() { data.pop(); minData.pop(); } int top() { return data.top(); } int min() { return minData.top(); } };用双向链表也是可以的
class Solution { public: struct ListNode{ int val; struct ListNode *pre; struct ListNode *next; ListNode(int val){ this->val = val; this->pre = NULL; this->next = NULL; } }; ListNode *head = NULL; ListNode *end = NULL; int minVal = INT_MAX; void push(int value) { ListNode *node = new ListNode(value); if(end == NULL){ head = node; end = node; }else{ end->next = node; node->pre = end; end = node; } if(value < minVal){ minVal = value; } } void pop() { bool flag = end->val == minVal; end = end->pre; end->next = NULL; if(flag){ ListNode *tmp = head; minVal = INT_MAX; while(tmp != NULL){ if(tmp->val < minVal){ minVal = tmp->val; } tmp = tmp->next; } } } int top() { return end->val; } int min() { return minVal; }