题目:
Design a 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 Stack<Integer>stack=new Stack<Integer>();
private Stack<Integer>minstack=new Stack<Integer>();
public void push(int x) {
stack.push(x);
if(minstack.size()!=0){
if(x<=minstack.peek()){
minstack.push(x);
}
}else{
minstack.push(x);
}
}
public void pop() {
int x=stack.pop();
if(x==minstack.peek()){
minstack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return minstack.peek();
}
}