Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
class MinStack {
private:
std::stack<int> stack;
std::stack<int> minstack;
public:
void push(int x) {
stack.push(x);
if(minstack.empty() || x <= minstack.top())
minstack.push(x);
}
void pop() {
if(!stack.empty())
{
if(minstack.top() == stack.top())
{
minstack.pop();
}
stack.pop();
}
}
int top() {
if(!stack.empty())
{
return stack.top();
}
}
int getMin() {
if(!minstack.empty())
{
return minstack.top();
}
}
};