题目:
![](https://i-blog.csdnimg.cn/blog_migrate/2544ff699bad471b0ab510cf196878e2.png)
题解 : 参考博客
![](https://i-blog.csdnimg.cn/blog_migrate/177fb2386bab5a83de9d53c5cc4cfbe4.png)
代码:
class MinStack {
stack<int> Main_stack;
stack<int> help_stack;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
Main_stack.push(x);
if(help_stack.empty()){ //辅协议栈空
help_stack.push(x);
}else{
if(Main_stack.top()<=help_stack.top()){ //辅协议栈非空,当前x入主栈值必须小于等于辅栈栈顶才可入辅栈
help_stack.push(x);
}
}
}
void pop() {
if(Main_stack.top()==help_stack.top()){
help_stack.pop();
}
Main_stack.pop();
}
int top() {
return Main_stack.top();
}
int min() {
return help_stack.top();
}
};
/**
* 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->min();
*/