题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.Scanner; import java.util.Stack; import java.util.regex.Pattern; import java.util.regex.Matcher; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); Stack<Integer> stack = new Stack<>(); for (int i = 0; i < n; i++) { String operation = scanner.next(); if (operation.equals("push")) { int num = scanner.nextInt(); stack.push(num); } else if (operation.equals("pop")) { if (stack.isEmpty()) { System.out.println("error"); } else { System.out.println(stack.pop()); } } else if (operation.equals("top")) { if (stack.isEmpty()) { System.out.println("error"); } else { System.out.println(stack.peek()); } } } scanner.close(); } }
对于Java语言来说这道题的解题重点更多的是在于对输入的考察
#每日一题挑战#每日一题解题思路 文章被收录于专栏
每天坚持刷题,从简单题开始,分享自己的解题思路。 期待您的关注。