向栈中存放元素:stack.push(); 获取栈顶元素:stack.peek(); 删除栈顶元素(返回值为删除的元素):stack.pop();
import java.util.Stack;
public class Solution {
//正常栈操作
private Stack<Integer> stack = new Stack<Integer>();
//保存最小值栈
private Stack<Integer> mins = new Stack<Integer>();
public void push(int node) {
stack.push(node);
//最小值栈为空或元素小于最小值栈顶元素则入栈
if(mins.isEmpty() || node <= mins.peek())
mins.push(node);
}
public void pop() {
//两个栈顶元素相同则最小值栈顶也需要弹出
if(stack.peek().equals(mins.peek()))
mins.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return mins.peek();
}
}