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();
            }
        }
    }
}
相关推荐
IT_陈寒44 分钟前
Vue的响应式把我坑惨了,原来问题出在这
前端·人工智能·后端
shark22222221 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
IGAn CTOU2 小时前
王炸级更新!Spring Boot 3.4 正式发布,新特性真香!
java·spring boot·后端
柯西劝我别收敛2 小时前
Koordinator-Scheduler 调度器源码解析
后端·云原生
tycooncool2 小时前
Spring中的IOC详解
java·后端·spring
303782 小时前
消息推送削峰落地方案
后端
爱敲代码的小黄2 小时前
我重新梳理了一遍 RAG,终于明白它不只是接个向量库
后端·面试·agent
亦暖筑序3 小时前
Spring AI Alibaba 报错合集:我踩过的那些坑
java·后端
石榴树下的七彩鱼3 小时前
OCR 识别不准确怎么办?模糊 / 倾斜 / 反光图片优化实战(附完整解决方案 + 代码示例)
图像处理·人工智能·后端·ocr·api·文字识别·图片识别
卜夋4 小时前
Rust 学习笔记 - Day 6: 引用与借用
后端·rust