题解 | #【模板】栈#

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int times = in.nextInt();
        MyStack stack = new MyStack(times);
        while (in.hasNext()) { // 注意 while 处理多个 case
            String op = in.next();
            
            if (op.equals("push")) {
                int value = in.nextInt();
                stack.push(value);
            } else if (op.equals("pop")) {
                try {
                    int result = stack.pop();
                    System.out.println(result);
                } catch(NullPointerException e) {
                    System.out.println("error");
                }
            } else if (op.equals("top")) {
                try {
                    int result = stack.top();
                    System.out.println(result);
                } catch(NullPointerException e) {
                    System.out.println("error");
                }
            }
            
        }
    }
}

class MyStack {
    int[] val;
    int top = -1;
    int maxSize;

    public MyStack(int maxSize) {
        this.maxSize = maxSize;
        this.val = new int[maxSize];
    }

    public boolean push(int x) {
        top += 1;
        val[top] = x;
        return true;
    }

    public int pop() {
        if (top == -1) {
            throw new NullPointerException("栈为空");
        }
        int result = val[top];
        val[top] = 0;
        top--;
        return result;
    }

    public int top() {
        if (top == -1) {
            throw new NullPointerException("栈为空");
        }
        int result = val[top];
        return result;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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