AcWing 829. 模拟队列

题目

实现一个队列,队列初始为空,支持四种操作:

  1. push x – 向队尾插入一个数 x
  2. pop – 从队头弹出一个数;
  3. empty – 判断队列是否为空;
  4. query – 查询队头元素。

现在要对队列进行 M个操作,其中的每个操作 33 和操作 44 都要输出相应的结果。

输入格式

第一行包含整数 M,表示操作次数。

接下来 M 行,每行包含一个操作命令,操作命令为 push xpopemptyquery 中的一种。

输出格式

对于每个 empty 和 query 操作都要输出一个查询结果,每个结果占一行。

其中,empty 操作的查询结果为 YES 或 NOquery 操作的查询结果为一个整数,表示队头元素的值。

数据范围

1≤M≤100000
1≤x≤10^9
所有操作保证合法。

输入样例:
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
输出样例:
NO
6
YES
4

代码


import java.util.Scanner;

public class Main {
   
    static int tt, hh = -1, M = 1000010;
    static int[] nums = new int[M];
    static void push(int x) {
   
        nums[++ hh] = x;
    }
    static void pop() {
   
        tt ++;
    }
    static String empty() {
   
        if (hh >= tt)   return "NO";
        else return "YES";
    }
    static void query() {
   
        System.out.println(nums[tt]);
    }
    public static void main(String[] args) {
   
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        while (m > 0) {
   
            m--;
            String s = in.next();
            if (s.equals("push")) {
   
                int x = in.nextInt();
                push(x);
            } else if (s.equals("empty")) {
   
                System.out.println(empty());
            } else if (s.equals("pop")) {
   
                pop();
            } else {
   
                query();
            }
        }
    }
}

相关推荐

  1. AcWing 829. 模拟队列

    2024-02-09 09:56:04       54 阅读
  2. Acwing---869. 试除法求约数

    2024-02-09 09:56:04       44 阅读
  3. 12.2 队列模拟

    2024-02-09 09:56:04       77 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-09 09:56:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-09 09:56:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-09 09:56:04       87 阅读
  4. Python语言-面向对象

    2024-02-09 09:56:04       96 阅读

热门阅读

  1. 深入挖掘AI应用场景的存储架构

    2024-02-09 09:56:04       59 阅读
  2. Python中数字和字符串的最佳实践(下)

    2024-02-09 09:56:04       51 阅读
  3. CDN缓存404、403状态码

    2024-02-09 09:56:04       42 阅读
  4. 数据结构之基数排序

    2024-02-09 09:56:04       55 阅读
  5. servlet和cgi区别

    2024-02-09 09:56:04       55 阅读
  6. Nginx 缓存集成、清除、设置不缓存资源

    2024-02-09 09:56:04       58 阅读
  7. 【FreeRTOS】堆栈管理:任务执行的基石

    2024-02-09 09:56:04       57 阅读
  8. C#阿里云消息列队推送消息

    2024-02-09 09:56:04       53 阅读