datastk
是数据栈,minstk
是辅助栈,每次进栈的时候都令辅助栈的栈顶为当前的最小值。
class MinStack {
public:
/** initialize your data structure here. */
stack<int> datastk,minstk;
MinStack() {
}
void push(int x) {
datastk.push(x);
if(minstk.empty()){
minstk.push(x);
}else{
int min=minstk.top();
minstk.push(x<min?x:min);
}
}
void pop() {
datastk.pop();
minstk.pop();
}
int top() {
return datastk.top();
}
int getMin() {
return minstk.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->getMin();
*/