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 {
public:
/** initialize your data structure here. */
stack<int>elements;
stack<int> minElement;
MinStack()
{
}
void push(int x)
{
if(minElement.empty())
{
minElement.push(x);
}
else
{
if(x <= minElement.top())
{
minElement.push(x);
}
}
elements.push(x);
}
void pop() {
if(!elements.empty())
{
if(elements.top() == minElement.top())
{
minElement.pop();
}
elements.pop();
}
}
int top() {
if(elements.empty())
{
return 0;
}
return elements.top();
}
int getMin() {
if(minElement.empty())
{
return 0;
}
return minElement.top();
}
};