題目:
定義棧的數(shù)據(jù)結(jié)構(gòu)博个,請在該類型中實現(xiàn)一個能夠得到棧中所含最小元素的min函數(shù)(時間復(fù)雜度應(yīng)為O(1))讹蘑。
import java.util.Stack;
public class Resolve {
Stack<Integer> stack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
public void push(int node) {
stack.push(node);
if(minStack.isEmpty() || node < minStack.peek()) {
minStack.push(node);
}else{
minStack.push(minStack.peek());
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}