题解 | #【模板】栈#

【模板】栈

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

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

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        scanner.nextLine();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < num; i++) {
            String operation = scanner.nextLine();
            if (operation.startsWith("push")) {
                int x = Integer.parseInt(operation.split(" ")[1]);
                stack.push(x);
            } else if (operation.equals("pop")) {
                if (!stack.isEmpty()) {
                    System.out.println(stack.pop());
                } else {
                    System.out.println("error");
                }
            } else if (operation.equals("top")) {
                if (!stack.isEmpty()) {
                    System.out.println(stack.peek());
                } else {
                    System.out.println("error");
                }
            }
        }
        scanner.close();
    }

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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