C++代码:
MinStack() {
}
void push(int x) {
sta1.push(x);
if(sta2.size()==0)
{
sta2.push(x);
}
else
{
if(sta2.top()<x)
{
sta2.push(sta2.top());
}
else
{
sta2.push(x);
}
}
}
void pop() {
sta1.pop();
sta2.pop();
}
int top() {
return sta1.top();
}
int getMin() {
return sta2.top();
}
public:
stack<int>sta1;
stack<int>sta2;
};
双栈,一栈正常执行操作,一栈栈顶元素为栈中最小元素。