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. */
MinStack():stackSize(0){ }
void push(int x) {
if(stackSize>=maxSize) cout<<"overFlow!"<<endl;
else{
stack[stackSize] = x;
if(stackSize==0) min[stackSize] = x;
else min[stackSize] = x<min[stackSize-1]?x:min[stackSize-1];
stackSize++;
}
}
void pop() {
stack[stackSize-1] = 0;
stackSize--;
}
int top() {
return stack[stackSize-1];
}
int getMin() {
return min[stackSize-1];
}
private:
int stackSize;
static const int maxSize = 800;
int stack[maxSize];
int min[maxSize];
};