定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))
import java.util.Stack;
public class Solution {
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minStack=new Stack<Integer>();
//每次放一個數的時候都要判斷最小棧中的數
public void push(int node) {
stack.push(node);
if (minStack.isEmpty()) {
minStack.push(node);
} else {
if (node <= minStack.peek()) {
minStack.push(node);
}
}
}
public void pop() {
if (stack.isEmpty()) {
return;
} else {
if (stack.pop() == minStack.peek()) {
minStack.pop();
}
}
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}