算法-实现 出入栈,寻找最小值
栈
先进后出
实现出栈入栈以及获取栈中最小值,主要是获取最小值
package algorithm.getminstack;
import java.util.Stack;
public class getMinStatck {
private static Stack<Integer> mainStack = new Stack<Integer>();
private static Stack<Integer> minStack = new Stack<Integer>();
public static void push(int element) {
mainStack.push(element);
//维护最小值栈
if (minStack.isEmpty()) {
minStack.push(element);
} else {
if (minStack.peek() >= element) {
minStack.push(element);
}
}
}
public static int pop() {
int temp = mainStack.pop();
//维护最小栈
if (temp == minStack.peek()) {
minStack.pop();
}
return temp;
}
public static int getMin() {
return minStack.peek();
}
public static void main(String[] args) {
// 4 9 7 3 8 5
push(4);
push(9);
push(7);
push(3);
push(8);
push(5);
System.out.println();
pop();
System.out.println();
getMin();
System.out.println();
}
}
需要注意的
维护最小值,在minstack中,是本题主要考察点
不恋尘世浮华,不写红尘纷扰