code-栈

leetcode-最小栈

用到一个辅助栈来存储最小值,注意点的就是两个栈是否同时弹出值

class MinStack
{
public:
MinStack() {
}
stack<int> s;
stack<int> Min;
void push(int x) {
if(Min.empty()||x<=Min.top())
{
Min.push(x);
}
s.push(x);
}
void pop() {
if(!s.empty())
{
if(Min.top()==s.top())
{
Min.pop();
s.pop();
}
else
s.pop();
}
}
int top() {
return s.top();
}
int getMin() {
return Min.top();
}

};

posted @ 2020-05-08 16:45  我爱微风  阅读(72)  评论(0)    收藏  举报