棧
先進(jìn)后出
實(shí)現(xiàn)出棧入棧以及獲取棧中最小值,主要是獲取最小值
package algorithm.getminstack;
import java.util.Stack;
public class getMinStatck {
private static Stack mainStack = new Stack();
private static Stack minStack = new Stack();
public static void push(int element) {
mainStack.push(element);
//維護(hù)最小值棧
if (minStack.isEmpty()) {
minStack.push(element);
} else {
if (minStack.peek() >= element) {
minStack.push(element);
}
}
}
public static int pop() {
int temp = mainStack.pop();
//維護(hù)最小棧
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();
}
}
需要注意的
維護(hù)最小值,在minstack中,是本題主要考察點(diǎn)