牛客网:AB8 【模板】循环队列

java JDK自带了队列对象,已经实现了队列,但是用java的jdk,哪还有什么意思呢?那直接使用队列不行了,这道题不就变成了你知道jdk怎么new一个队列吗?这样连简单题都算不上把。所以我觉得我应该自己实现一个队列的对象,使用数组来模拟这个队列。

思路:定一个队列对象,然后定义三个参数,一个是新增下标,一个是删除队列的下标,还有一个是判断队列空还是满的下标。队列是否满,其实只需要看最后一个下标就行了。

代码如下

package com.算法专练.牛客网.循环队列;

import java.util.Scanner;

/**
 * @author xnl
 * @Description:
 * @date: 2022/5/27   20:10
 */
public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 第一行的值, 下标0的值我们拿来初始化队列,下标1的值代表我们的操作数
        String str = scanner.nextLine();
        String[] split = str.split("\\s+");
        MyQueue queue = new MyQueue(Integer.parseInt(split[0]));

        for (int i = 0; i < Integer.parseInt(split[1]); i++) {
            // 记录输入的值
            String[] input = scanner.nextLine().split("\\s+");

            String temp = input[0];
            if (temp.equals("push")) {
                queue.push(Integer.parseInt(input[1]));
            } else if (temp.equals("pop")) {
                queue.pop();
            } else if (temp.equals("front")) {
                queue.front();
            } else {
                return;
            }
        }

    }
}

class MyQueue {
    private int size;
    private int[] queue;
    private int index;
    private int popIndex = 0;
    private int diff;

    public MyQueue() { }

    public MyQueue(int size) {
        this.size = size;
        this.queue = new int[size];
        this.index = 0; // 记录指针下标
        this.diff = 0; // 差值
        this.popIndex = 0;
    }

    private boolean isEmpty() {
        return diff == 0 ;
    }

    public void push(int value) {
        if (diff == size) {
            System.out.println("full");
            return;
        }
        queue[index] = value;
        index = (index + 1) % size;
        diff++;
    }

    public void pop() {
        if (isEmpty()) {
            System.out.println("empty");
            return;
        }
        System.out.println(queue[popIndex]);
        popIndex = (popIndex + 1) % size;
        diff--;
    }

    public void front() {
        if (isEmpty()) {
            System.out.println("empty");
            return;
        }
        System.out.println(queue[popIndex % size]);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值