java数组两种方法实现循环队列

一、通过空置一个元素区分队列满和队列空

public class ArrayQueueEmptyOneElement<T> {
    private int size = 0;

    private int startIndex = 0;

    private int endIndex = 0;

    private Object[] array = null;

    public ArrayQueueEmptyOneElement(int size) {
        //因为要空置一位,所以实际数组长度要加一
        this.size = size + 1;
        array = new Object[size + 1];
    }

    public boolean offer(T t){
        if (isFull()){
            System.out.println("队列已满。。。");
            return false;
        }
        array[endIndex] = t;
        endIndex = (endIndex + 1) % size;
        return true;
    }

    public T poll(){
        if (isEmpty()){
            System.out.println("队列是空的。。。");
            return null;
        }
        T t = (T) array[startIndex];
        array[startIndex] = null;
        startIndex = (startIndex + 1) % size;
        return t;
    }

    public boolean isFull(){
        return (endIndex + 1) % size == startIndex;
    }

    public boolean isEmpty(){
        return startIndex == endIndex;
    }
}

二、通过队列中实际元素个数判断队列是否满(无空置元素)

public class ArrayQueueNoEmptyElement<T> {
    private int count = 0;

    private int startIndex = 0;

    private int endIndex = 0;

    private Object[] array = null;

    public ArrayQueueNoEmptyElement(int size) {
        array = new Object[size];
    }

    public boolean offer(T t){
        if (isFull()){
            System.out.println("队列已满。。。");
            return false;
        }
        array[endIndex] = t;
        endIndex = (endIndex + 1) % array.length;
        count++;
        return true;
    }

    public T poll(){
        if (isEmpty()){
            System.out.println("队列是空的。。。");
            return null;
        }
        T t = (T) array[startIndex];
        array[startIndex] = null;
        startIndex = (startIndex + 1) % array.length;
        count--;
        return t;
    }

    public boolean isFull(){
        return count == array.length;
    }

    public boolean isEmpty(){
        return count == 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值