import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
String operation = scanner.next();
if (operation.equals("push")) {
int num = scanner.nextInt();
stack.push(num);
} else if (operation.equals("pop")) {
if (stack.isEmpty()) {
System.out.println("error");
} else {
System.out.println(stack.pop());
}
} else if (operation.equals("top")) {
if (stack.isEmpty()) {
System.out.println("error");
} else {
System.out.println(stack.peek());
}
}
}
scanner.close();
}
}
对于Java语言来说这道题的解题重点更多的是在于对输入的考察

京公网安备 11010502036488号