队列2——环形队列实现

本文详细介绍了如何使用Java编程语言实现环形队列,包括其数据结构设计和关键操作的代码实现,旨在帮助读者理解环形队列的工作原理及其在实际问题中的应用。
摘要由CSDN通过智能技术生成

环形队列示意

public class CycleQueue {
   
    /**
     * 1、frontIndex指向队首第一个元素,frontIndex=0
     * 2、rearIndex指向最后一个元素后一个位置,即队列末尾的空指针,这样可以留一个位置作为约定
     *      rearIndex=0
     * 3、队空判断:rearIndex==frontIndex
     * 4、队满判断:(rearIndex+1)%maxSize==frontIndex
     * 5、队列有效的元素个数(rearIndex+maxSize-frontIndex)%maxSize
     */
    private int maxSize;
    private int frontIndex;
    private int rearIndex;
    private int[] cycleQueue;

    /**
     * 生成队列
     * @param maxSize
     */
    public void queue(int maxSize){
   
        this.maxSize=maxSize;
        cycleQueue=new int[maxSize];
    }

    /**
     * 判断队列为空
     * @return
     */
    public boolean isEmpty(){
   
        return frontIndex == rearIndex;
    }

    /**
     * 判断队列是否满
     * @return
     */
    public boolean isFull(){
   
        return (rearIndex+1)%maxSize == frontIndex;
    }

    /**
     * 添加数据
     * 因为rearIndex已经指向队列后的空位置,所以先赋值,再移动
     * 同时环形队列,rearIndex会移动到队首,所以需要取余
     * @param element
     */
    public void addElement(int element){
   
        if(isFull()){
   
            System.out.println("队列已满,添加失败");
        }else {
   
            cycleQueue[rearIndex]=element;
            rearIndex<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值