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 LinkedList<Integer> stack=new LinkedList<Integer>();
int min=Integer.MAX_VALUE; // if it's min the initial value should be max
public void push(int x) {
stack.add(x);
if(x<min)min=x;
}
public void pop() {
Integer cur=stack.removeLast();
if(cur==min){
min=Integer.MAX_VALUE; // this should be max
for(Integer a:stack){
if(a<min)min=a;
}
}
}
public int top() {
return stack.get(stack.size()-1);
}
public int getMin() {
return min;
}
}