题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.Scanner;
import java.util.Stack;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < num; i++) {
String operation = scanner.nextLine();
if (operation.startsWith("push")) {
int x = Integer.parseInt(operation.split(" ")[1]);
stack.push(x);
} else if (operation.equals("pop")) {
if (!stack.isEmpty()) {
System.out.println(stack.pop());
} else {
System.out.println("error");
}
} else if (operation.equals("top")) {
if (!stack.isEmpty()) {
System.out.println(stack.peek());
} else {
System.out.println("error");
}
}
}
scanner.close();
}
}


小天才公司福利 1282人发布