题解 | #【模板】栈#

【模板】栈

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

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        s.nextLine();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            String str = s.nextLine();
            if (str.contains("push")){
                // 表示这个字符串是进行入栈操作
                Integer num = Integer.valueOf(str.split(" ")[1]);
                stack.push(num);
                continue;
            }
            switch (str){
                case "pop":{
                    if (stack.isEmpty()){
                        System.out.println("error");
                    }else {
                        System.out.println(stack.pop());
                    }
                     break;
                }
               
                case "top":{
                    if (stack.isEmpty()) {
                        System.out.println("error");
                    }else {
                        System.out.println(stack.peek());
                    }
                }
            }
        }
    }
}

#我的求职思考##在找工作求抱抱#
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务