Acwing---829. 模拟队列

1.题目

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

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

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

输入格式
第一行包含整数 M M M,表示操作次数。

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

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

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

数据范围
1 ≤ M ≤ 100000 , 1≤M≤100000, 1M100000,

1 ≤ x ≤ 109 , 1≤x≤109, 1x109,

所有操作保证合法。 所有操作保证合法。 所有操作保证合法。

输入样例:

10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6

输出样例:

NO
6
YES
4

2.基本思想

用一个数组 q 保存数据。

hh 代表队头,q[hh] 就是队头元素, q[hh + 1] 就是第二个元素。

tt代表队尾, q[tt] 就是队尾元素, q[tt + 1] 就是下一次入队,元素应该放的位置。

[hh, tt] 左闭右闭,代表队列中元素所在的区间。

出队pop:因为 hh 代表队头,[hh, tt] 代表元素所在区间。所以出队可以用 hh++实现,hh++后,区间变为[hh + 1, tt]

入队push:因为 tt 代表队尾,[hh, tt] 代表元素所在区间。所以入出队可以用 tt++实现,tt++后,区间变为[hh, tt + 1], 然后在q[tt+1]位置放入入队元素。

是否为空empty:[hh, tt] 代表元素所在区间,当区间非空的时候,对列非空。也就是tt >= hh的时候,对列非空。

询问队头query:用 hh 代表队头,q[hh] 就是队头元素,返回 q[hh] 即可。

在这里插入图片描述

3.代码实现

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static int N = 100010;
    static int[] q = new int[N];
    static int hh, tt = -1;//分别表示 对头0  队尾-1

    public static void main(String[] args) throws IOException {
        int m = Integer.parseInt(br.readLine());
        while (m-- > 0) {
            String[] s = br.readLine().split(" ");
            String opt = s[0];
            if (opt.equals("push")) {
                int x = Integer.parseInt(s[1]);
                q[++tt] = x;
            } else if (opt.equals("pop")) {
                hh++;
            } else if (opt.equals("empty")) {
                System.out.println(tt >= hh ? "NO" : "YES");
            } else if (opt.equals("query")) {
                System.out.println(q[hh]);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

amant 柒少

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值