题解 | #【模板】栈#

【模板】栈

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
     int[] stack = new int[100000];
     int top = -1;
     void push(int x) {
        top += 1;
        stack[top] = x;
    }
     void pop() {
        if (top == -1) {
            System.out.println("error");
            return;
        }
        System.out.println(stack[top]);
        top -= 1; 
    }
     void top() {
        if (top == -1) {
            System.out.println("error");
            return;
        }
        System.out.println(stack[top]);
    }
    public static void main(String[] args) {
        Main m = new Main();
        Scanner in = new Scanner(System.in);
        String count = in.nextLine();
        while (in.hasNextLine()) {
            String test = in.nextLine();
            if("pop".equals(test)){
                m.pop();
            }else if("top".equals(test)){
                m.top();
            }else{
                String[] test2 = test.split(" ");
                m.push(Integer.parseInt(test2[1]));
            }
        }
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
    }
}

全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务