题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.Scanner;
import java.util.ArrayList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
int a = Integer.valueOf(in.nextLine());
Stack mySt = new Stack(a);
for(int i = 0;i<a;i++){
String str = in.nextLine();
mySt.operate(str);
}
}
}
}
class Stack {
//private int size = 0;
private int maxSize;
private int[] data;
private int topIndex = -1;
public Stack(int maxSize) {
this.maxSize = maxSize;
this.data = new int[maxSize];
}
public void top() {
if (this.topIndex == -1) {
System.out.println("error");
} else {
System.out.println(data[topIndex]);
}
}
public void push(int num) {
if (this.topIndex == maxSize) {
System.out.println("error");
} else {
this.topIndex++;
this.data[topIndex] = num;
}
}
public void pop() {
if (this.topIndex == -1) {
System.out.println("error");
} else {
System.out.println(this.data[topIndex]);
this.topIndex--;
}
}
public void operate(String opStr) {
String[] strArr = opStr.split(" ");
switch (strArr[0]) {
case "push":
this.push(Integer.valueOf(strArr[1]));
break;
case "pop":
this.pop();
break;
case "top":
this.top();
break;
default:
break;
}
}
}