题解 | 2024_堆栈基本操作_1745直接用栈模拟就行

2024_堆栈基本操作_1745

https://www.nowcoder.com/practice/7b6806aa9c304f32972175c954957051

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Stack<Integer> stack = new Stack<>();
        int seq = 1;
        List<String> ans = new LinkedList<>();
        while (n-- > 0) {
            int x = sc.nextInt();
            while (seq <= x) {
                stack.push(seq);
                ans.add("PUSH " + seq);
                seq++;
            }
            if (!stack.empty() && stack.peek() == x) {
                stack.pop();
                ans.add("POP " + x);
            } else {
                System.out.println("NO");
                return;
            }
        }
        for (String s : ans) System.out.println(s);
        sc.close();
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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