记得用BufferedReader配合InputStreamReader优化输入时间,这题比较Scanner输入,时间优化300ms左右,比例近二分之一

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Stack {
    // 指针
    int p;
    // 栈最大容量
    int max;
    // 栈数据
    int[] data;

    // 初始化栈
    public Stack(int max) {
        this.max = max;
        data = new int[max];
        p = 0;
    }
    // 入栈
    public void push(int n) {
        if (p == max) {
            System.out.println("error");
            return;
        }
        data[p] = n;
        p++;
    }
    // 出栈
    public void pop() {
        if (p == 0) {
            System.out.println("error");
        } else {
            p--;
            System.out.println(data[p]);
        }

    }
    // 查看栈顶
    public void top() {
        if (p == 0) {
            System.out.println("error");
        } else{
            System.out.println(data[p - 1]);
        }
    }
}

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // 输入的一行、操作
        String s, operate;
        // 操作数
        int n;
        // 栈最大值
        int max = Integer.parseInt(in.readLine());
        Stack stack = new Stack(max);

        while ((s = in.readLine()) != null) { // 注意 while 处理多个 case
            operate = s.split(" ")[0];
            // System.out.print(s);
            if ("push".equals(operate)) {
                n = Integer.parseInt(s.split(" ")[1]);
                stack.push(n);
            } else if ("pop".equals(operate)) {
                stack.pop();
            } else {
                stack.top();
            }
        }
    }
}