Skip to content

Instantly share code, notes, and snippets.

@mikeyang01
Created February 22, 2019 09:24
Show Gist options
  • Save mikeyang01/3cc6d866f8e2e6240e19c6c426a601ff to your computer and use it in GitHub Desktop.
Save mikeyang01/3cc6d866f8e2e6240e19c6c426a601ff to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class Stack_MiniStack {
//声明一个data栈
private static Stack<Integer> dataStack = new Stack<>();
//声明一个min栈
private static Stack<Integer> minStack = new Stack<>();
//入栈
public static void push(int num) {
//1.入栈有两种情况
//1.1 栈为空,那么第一个数直接进data栈和min栈
//1.2 栈不为空,data栈正常入,入min栈的时候,先与min栈的栈顶数据进行比较,小的数入min栈
if (dataStack.isEmpty()) {//栈为空
dataStack.push(num);
minStack.push(num);
} else {//栈不为空
dataStack.push(num);
if (num < minStack.peek()) {
minStack.push(num);
} else {
minStack.push(minStack.peek());
}
}
}
//弹栈
public static Integer pop() {
//弹栈的时候,data栈和min栈一起弹出,如果栈为空,则先提醒用户
if (dataStack.isEmpty()) {
throw new IllegalArgumentException("栈已空");
}
minStack.pop();
return dataStack.pop();
}
//取最小值
public static Integer getMin() {
//直接获取最小栈的数据即可,如果栈为空,则先提醒用户
if (dataStack.isEmpty()) {
throw new IllegalArgumentException("栈已空");
}
return minStack.peek();
}
public static void main(String[] args) {
int[] a = {1, 2, 3};
for (int i = 0; i < a.length; i++) {
push(a[i]);
System.out.println(a[i] + " ");
}
System.out.println("pop:" + pop());
System.out.println("getMini:" + getMin());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment