class MinStack {
public:
void push(int x) {
if (x <= min_) {
st_.push(min_);
min_ = x;
}
st_.push(x);
}
void pop() {
if (st_.top() == min_) {
st_.pop();
min_ = st_.top();
st_.pop();
} else st_.pop();
}
int top() { return st_.top(); }
int getMin() { return min_; }
private:
stack<int> st_;
int min_ = INT_MAX;
};
C++ Solution



@johnmclain I think the main point of the problem was to implement Min operation. Just to implement stack is very simple, it wasn't the point of the problem, you can easily implement stack with very few operations using regular array and it wouldn't much differ from my solution using STL stack. But to implement Min operation needs thinking, so I didn't focus on implementing a regular stack, but only the Min operation.