题解 | 【模板】栈
【模板】栈
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);
ArrayList<Integer> array=new ArrayList<Integer>();
int n=in.nextInt();
// 注意 hasNext 和 hasNextLine 的区别
while (n>0) { // 注意 while 处理多个 case
String a = in.next();
if(a.startsWith("push"))
{
int b=in.nextInt();
array.add(b);
}
else if(a.equals("pop"))
{
if(array.isEmpty())
{
System.out.println("error");
}
else
{
int lastIndex=array.size()-1;
System.out.println(array.get(lastIndex));
array.remove(lastIndex);
}
}
else if(a.equals("top"))
{
if(array.isEmpty())
{
System.out.println("error");
}
else
{
int lastIndex=array.size()-1;
System.out.println(array.get(lastIndex));
}
}
n--;
}
}
}

快手成长空间 763人发布