题解 | 没用stack库

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = 0; //获取到操作总数,来单独判断输入的第一行信息
        int index = -1;  // 定义一个指针,指向栈顶元素
        ArrayList<Integer> list = new ArrayList<>();
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            if (num == 0) {num = in.nextInt();}
            else {
                String opr = in.nextLine(); // 第一行之后的所有操作
                if (opr.contains("pop")) { // 没有定义新的class所以就简单用contains判断了
                    if(index == -1) {
                        System.out.println("error"); // 没有数据的情况
                    } else {
                        System.out.println(list.get(index)); // 输出栈顶元素,并删除之,指针跟随减少1
                        list.remove(index);
                        index--;
                    }
                } else if (opr.contains("push")) {
                    index++;
                    String[] temp = opr.split(" "); // 简单用分割拿到后面的数字
                    list.add(index, Integer.parseInt(temp[1]));
                } else if (opr.contains("top")) {
                    if(index == -1) {
                        System.out.println("error");
                    } else {
                        System.out.println(list.get(index));
                    }
                } else {
                }
            }
        }
    }
}

没有用到自带的stack库,因为觉得本身就是理解栈的使用,直接用自带的栈库就没什么意义了。所以手搓了一下简易的栈。

全部评论

相关推荐

废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务