包含min的函数栈
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
public class Solution {
private Stack<Integer> stack=new Stack<>();
private Stack<Integer> minStack=new Stack<>();
private int min=Integer.MAX_VALUE;
public void push(int node) {
stack.push(node);
if(min>node)min=node;
minStack.push(min);
}
public void pop() {
stack.pop();
minStack.pop();
min=minStack.peek();
}
public int top() {
return stack.peek();
}
public int min() {
return min;//用min不保险,可能还没有往里放元素,用peek更好。
}
}