题解 | #设计getMin功能的栈#
设计getMin功能的栈
https://www.nowcoder.com/practice/05e57ce2cd8e4a1eae8c3b0a7e9886be
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
//正常保存数字的栈
Stack<Long> stackNum = new Stack<>();
//保存最小值的栈
Stack<Long> stackMIn = new Stack<>();
Scanner in = new Scanner(System.in);
int N = in.nextInt();
for (int i = 0; i < N; i++) {
String str = in.next();
if (str.startsWith("push")) {
long num = in.nextInt();
stackNum.push(num);
//最小栈入栈的时机
if (stackMIn.isEmpty() || num <= stackMIn.peek()) {
stackMIn.push(num);
}
} else if (str.startsWith("pop")) {
long popNum = stackNum.pop();
//最小栈弹出的时机
if (popNum == stackMIn.peek()) {
stackMIn.pop();
}
} else if (str.startsWith("getMin")) {
System.out.println(stackMIn.peek());
}
}
}
}
栈和队列,记录栈和队列的一些题 文章被收录于专栏
栈和队列,记录栈和队列的一些题


