题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
int[] stack = new int[100000];
int top = -1;
void push(int x) {
top += 1;
stack[top] = x;
}
void pop() {
if (top == -1) {
System.out.println("error");
return;
}
System.out.println(stack[top]);
top -= 1;
}
void top() {
if (top == -1) {
System.out.println("error");
return;
}
System.out.println(stack[top]);
}
public static void main(String[] args) {
Main m = new Main();
Scanner in = new Scanner(System.in);
String count = in.nextLine();
while (in.hasNextLine()) {
String test = in.nextLine();
if("pop".equals(test)){
m.pop();
}else if("top".equals(test)){
m.top();
}else{
String[] test2 = test.split(" ");
m.push(Integer.parseInt(test2[1]));
}
}
// 注意 hasNext 和 hasNextLine 的区别
// while (in.hasNextInt()) { // 注意 while 处理多个 case
// int a = in.nextInt();
// int b = in.nextInt();
// System.out.println(a + b);
// }
}
}

