Use another stack to save all minimum numbers. Then while popping, the corresponding minimum number can be popped, and the minimum number is always the top of that stack.
class MinStack {
public:
void push(int x) {
st.push(x);
if(min.empty()||x<=min.top())
min.push(x);
}
void pop() {
if(st.top()==min.top())
min.pop();
st.pop();
}
int top() {
return st.top();
}
int getMin() {
return min.top();
}
private:
stack<int> st;
stack<int> min;
};