import java.util.Stack; /** * 具有getmin功能的栈 * @author lenovo047 * */
public class test21 { private static Stack<Integer> stackData = new Stack<>(); private static Stack<Integer> stackMin = new Stack<>(); public static void push(int num){ if(stackMin.isEmpty()){ //栈为空,直接放进去 stackMin.push(num); } else if(stackMin.peek() > num){ //新数比栈顶元素小,放新数 stackMin.push(num); } else { //新数比栈顶元素大,放老数 stackMin.push(stackMin.peek()); //peek只是复制这个数 } stackData.push(num); } public static int pop(){ if(stackData.isEmpty()){ throw new RuntimeException("栈为空"); } stackMin.pop(); return stackData.pop(); } public static int getMin(){ if(stackMin.isEmpty()){ throw new RuntimeException("栈为空"); } return stackMin.peek(); }
}