题目链接:155. 最小栈
2020.10.15第一次解答:
解题思路
个人以为实现一个最小栈就不能用STL的栈,于是定义了一个链表结构体写的栈...一看题解,嗯?还能这样?
但是用自定义链表的速度就很快哈哈哈哈哈
C++代码
class MinStack {
private:
int min;
struct node {
int val;
node* pre;
};
node* cur;
public:
/** initialize your data structure here. */
MinStack() {
min = INT_MAX;
cur = nullptr;
}
void push(int x) {
node* tmp = new node;
if (!cur) {
tmp->pre = nullptr;
tmp->val = x;
}
else {
tmp->pre = cur;
tmp->val = x;
}
cur = tmp;
if (x < min) min = x;
}
void pop() {
//需要考虑元素出栈后,最小栈值有没有改变
if (cur->val == min) {
int min2 = INT_MAX;
node* tmp = cur->pre;
while (tmp) {
if (tmp->val < min2) {
min2 = tmp->val;
}
tmp = tmp->pre;
}
min = min2;
delete(tmp);
}
node* tmp = cur;
cur = cur->pre;
delete(tmp);
}
int top() {
return cur->val;
}
int getMin() {
return min;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/