数组实现环形队列

数组实现环形队列

一.队列概念

1)队列是一个有序列表,可以使用数组或者链表方式实现
2)队列遵循先进先出原则!
在这里插入图片描述

数组实现分析

图中我们将 头节点指向第一个元素(也就是头节点元素)
尾节点指向尾元素的下一个节点
为了实现环形队列我们需要采用取模方式计算头/尾节点位置

代码实现

/**
 * 环形队列
 * */
public class CyclicArrayQueue {
    private int maxSize;//总容量
    private int head;//头节点
    private int tail;//尾节点
    private int [] arrayQueue;//定义初始数组
    public CyclicArrayQueue(int arraySize){
        this.maxSize = arraySize;
        //头节点指向第一个元素(就是头节点元素)
        head =0;
        //尾节点指向最后元素的下一个节点
        tail = 0;
        //尾节点指向最后元素的下一个节点所以需要+1来设置构造函数传递过来的实际数组容量
        arrayQueue = new int [++this.maxSize] ;
    }
    /**
     * 判断队列是否为空
     * */
    public Boolean isEmply(){
        return head == tail;
    }
    /**
     * 判断队列是否已满
     * */
    public Boolean isFull(){
        //如果(尾节点+1)%总容量=头节点则队列已满(尾节点预留了一个空间)
        return (tail+1)%maxSize == head;
    }
    /**
     * 获取队列中有效数据数量
     * */
    public int getNums(){
        //(尾节点-头节点+总容量)%总容量
        return (tail-head+maxSize)%maxSize;
    }
    /**
     * 添加一个元素
     * */
    public int addQueue(int value){
        //判断是否已满
        if(isFull()){
            throw new RuntimeException("队列已满");
        }
        //因为尾节点已经指向了尾节点的下一个元素所以直接进行新增即可
        arrayQueue[tail] = value;
        //把尾节点向后移,这里不可以直接加1防止数组越界使用取模方式
        tail = (tail+1)%maxSize;
        return value;
    }
    /**
     * 取出一个元素
     * */
    public int getQueue(){
        //判断数组是否为空
        if(isEmply()){
            throw new RuntimeException("队列为空");
        }
        //头节点已经指向了当前头节点 这里需要定义一个变量用于接收头节点的值
        int headValue = arrayQueue[head];
        //然后把head后移一位
        head = (head+1)%maxSize;
        return headValue;
    }
    /**
     * 遍历
     * */
    public void ergodic(){
        for(int i = head;i<head+getNums();i++){
            System.out.println(arrayQueue[(i+maxSize)%maxSize]);
        }
    }
}

测试

public static void main(String[] args) {
        CyclicArrayQueue cyclicArrayQueue = new CyclicArrayQueue(3);
        cyclicArrayQueue.addQueue(10);
        cyclicArrayQueue.addQueue(20);
        cyclicArrayQueue.addQueue(30);
        System.out.println("遍历-------------------------------");
        cyclicArrayQueue.ergodic();
        int queue = cyclicArrayQueue.getQueue();
        int queue1 = cyclicArrayQueue.getQueue();
        System.out.println("获取元素:"+queue+"----"+queue1);
        cyclicArrayQueue.addQueue(1000);
        cyclicArrayQueue.addQueue(60);
        System.out.println("遍历-------------------------------");
        cyclicArrayQueue.ergodic();
        int nums = cyclicArrayQueue.getNums();
        System.out.println("有效数量:"+nums);
    }

输出
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值