AcWing 829. 模拟队列

题目

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

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

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

输入格式

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

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

输出格式

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

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

数据范围

1≤M≤100000 1≤x≤10^9

所有操作保证合法。

输入样例:

perl 复制代码
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6

输出样例:

objectivec 复制代码
NO
6
YES
4

代码

java 复制代码
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();
            }
        }
    }
}
相关推荐
小江的记录本2 分钟前
【泛型】泛型:泛型擦除、通配符、上下界限定
java·windows·spring boot·后端·spring·maven·mybatis
pupudawang3 分钟前
springboot下使用druid-spring-boot-starter
java·spring boot·后端
lierenvip15 分钟前
Spring Boot 自动配置
java·spring boot·后端
didiplus9 小时前
Python 入门第一课:为什么选择 Python?3 分钟搭建你的第一个程序
后端
dreamxian9 小时前
苍穹外卖day11
java·spring boot·后端·spring·mybatis
华科易迅10 小时前
Spring装配对象方法-注解
java·后端·spring
AwesomeDevin11 小时前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构
Victor35611 小时前
MongoDB(60)如何使用explain命令?
后端
Victor35611 小时前
MongoDB(59)如何分析查询性能?
后端