重学java数据结构--队列(循环数组实现)

队列:一个有序列表,实现方式有两种—循环数组/链表

特点:先进先出(FIFO)

实现方式:循环数组

首先明确两个基本约定:

  • 数组为空/满的判断:rear % maxsize == front(数组满);rear == front(数组空)
  • 数组有效数据的个数:rear - front

说明:

  1. rear指向数组最后一个元素下一位,即当第一个数字填入数组时,front=0&rear=1;当第8个数字填入数组的时候,front=7&rear=8;
  2. 数组中的下标统一用,“尾:【rear%maxsize】”和“头:【front%maxsize】”表示

在这里插入图片描述

示例代码:

public class MyQueue{
    //定义Queue内部属性
    private int[] interArray;
    private int Maxsize;
    private int front;
    private int rear;

    //创建队列的构造器
    public MyQueue(int maxsize){
        interArray = new int[maxsize];
        Maxsize = maxsize;
        front = 0;
        rear = 0;
    }

    //队列的几个常用方法
    //判断为空
    public boolean isEmpty(){
        return front == rear;
    }
    //判断为满
    public boolean isFull(){
        return (rear % Maxsize) == front;
    }
    //返回有效数据的个数
    public int getNum(){
        return rear - front;
    }
    //往队列存入一个数字
    public void add(int addNum){
        if (isEmpty()){
            interArray[rear%Maxsize] = addNum;
            rear++;
        }else {
            if (isFull()){
                throw new RuntimeException("队列已满,不能加入数据");
            }else {
                interArray[rear%Maxsize] = addNum;
                rear++;
            }
        }
    }

    //取出一个数字
    public int get(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,无有效数据");
        }else {
            int getid = front%Maxsize;
            front++;
            return interArray[getid];
        }
    }
    //打印所有的数据
    public void getAll(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,无有效数据");
        }else {
            for (int i = front; i < rear; i++){
                System.out.println(interArray[i%Maxsize]);
            }
        }
    }
}


public class QueueDemo {
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue(3);
        myQueue.add(4);
        myQueue.add(18);
        myQueue.add(92);
//        System.out.println(myQueue.get()+"===========");
        myQueue.add(12);
        myQueue.getAll();
//        myQueue.add(123);
//        System.out.println(myQueue.get());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值