题解 | 2024_堆栈基本操作_1745直接用栈模拟就行
2024_堆栈基本操作_1745
https://www.nowcoder.com/practice/7b6806aa9c304f32972175c954957051
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Stack<Integer> stack = new Stack<>();
int seq = 1;
List<String> ans = new LinkedList<>();
while (n-- > 0) {
int x = sc.nextInt();
while (seq <= x) {
stack.push(seq);
ans.add("PUSH " + seq);
seq++;
}
if (!stack.empty() && stack.peek() == x) {
stack.pop();
ans.add("POP " + x);
} else {
System.out.println("NO");
return;
}
}
for (String s : ans) System.out.println(s);
sc.close();
}
}

查看9道真题和解析