算法思想很简单,使用额外的一个栈保存最小值,与最小值相等的也保存,两点需要注意的:(网上有人说可以只是一个栈或者不使用STL中的stack直接实现待做!!)
1.使用C++ STL中的stack
2.stack的命名要注意,不能使用stack
class MinStack {
private:
stack<int> stacks;
stack<int> min;
public:
void push(int x) {
stacks.push(x);
if(min.empty() || min.top() >= x)
min.push(x);
}
void pop() {
if(!min.empty() && min.top() == stacks.top())
min.pop();
stacks.pop();
}
int top() {
if(!stacks.empty())
return stacks.top();
}
int getMin() {
if(!min.empty())
return min.top();
}
};