题解 | #【模板】栈#

【模板】栈

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);
        // }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
07-10 11:08
门头沟学院 Java
Sairus:我注册都注册不了提醒我手机号二次啥的,果然对于人才推得就是快,像我投完了就没回音的
投递京东等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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