题目链接:https://leetcode-cn.com/problems/min-stack/
使用语言:Java
class MinStack {
Stack<Integer> st = new Stack<Integer>();
Stack<Integer> st2 = new Stack<Integer>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
st.push(x);
if(st2.isEmpty()||x<=st2.peek()){
st2.push(x);
}
}
public void pop() {
int x = st.pop();
if(!st2.isEmpty()&&st2.peek()==x)st2.pop();
}
public int top() {
return st.peek();
}
public int getMin() {
if(!st2.isEmpty()){
return st2.peek();
}else if(!st.isEmpty()){
return st.peek();
}else{
return 0;
}
}
}