package sort;
import java.util.Stack;
public class Test30 {
public static Stack<Integer> stack = new Stack<Integer>(); // 用于存放所有数
public static Stack<Integer> storemin = new Stack<Integer>();// 用于存放当前栈的最小数实现O(1)取最小数
public static void push(int s) {// 放元素时主栈直接放,辅助栈需要一些比较,比栈顶元素小再放,否则再次存放栈顶元素,
// 保证辅助栈栈顶永远是最小的数
stack.push(s);
if (storemin.isEmpty()) {
storemin.push(s);
} else if (storemin.peek() > s) {
storemin.push(s);
} else if (storemin.peek() <= s) {
storemin.push(storemin.peek());
}
}
public static int pop() { // 需要同时取两个栈的栈顶元素,返回主栈的栈顶元素
if (!stack.isEmpty() && !storemin.isEmpty()) {
storemin.pop();
return stack.pop();
}
return 0;
}
public static int min() {// 直接去辅助栈的栈顶,复杂度为O(1);
return storemin.peek();
}
public static void main(String[] args) {
push(3);
push(4);
push(5);
System.out.println(min());
System.out.println(pop());
System.out.println(min());
System.out.println(pop());
System.out.println(pop());
}
}