循环队列代码实现

import java.util.NoSuchElementException;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName CyclicArrayQueue.java
 * @Description TODO
 * @createTime 2021年08月21日 19:46:00
 */
public class CyclicArrayQueue<E> {
    private int front;//队首
    private int rear;//队尾
    private E[] data;
    //容量,但是循环队列中,要空出一个位置方便表示队列的状态。rear=front队列为空
    private int maxSize;
    //构造器
    public CyclicArrayQueue(int capacity){//capacity为数组实际可以存储元素的大小
        this.front=0;
        this.rear=0;
        this.maxSize=capacity+1;
        this.data=(E[])new Object[maxSize];//不能直接用E[]造数组
    }
    //判断是否已经满了
    public boolean isFull(){
        return (rear+1)%maxSize==front;
    }
    //判断是否为空
    public boolean isEmpty(){
        return front==rear;
    }
    //获取大小
    public int size(){
        return (rear-front+maxSize)%maxSize;//复习的时候一定要看
    }
    //添加元素
   public void add(E e){
        if (e==null){
            throw new NullPointerException("添加的元素不能为空");
        }
        if(isFull()){
            throw new IllegalStateException("队列已经满了");
        }
        data[rear]=e;
        rear=(rear+1)%maxSize;//取模,防止rear是最后一个位置导致溢出,满了取前面的位置
   }
   //取出队列第一个元素
    public E get(){
        if (isEmpty()){
        throw new NoSuchElementException();
        }
        E e=data[front];
        front=(front+1)%maxSize;
        return e;
    }
    //查看队列第一个元素
    public E peek(){
        if (isEmpty()){
            throw new NoSuchElementException();
        }
        return data[front];
    }
    @Override//重写toString方法
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        if(isEmpty()){
            return buffer.append("[]").toString();
        }

        buffer.append("[");
        for (int i = front; i < front + size(); i++) {
            buffer.append(data[i%maxSize]).append(",");
        }
        // 删除最后一个逗号
        buffer.deleteCharAt(buffer.length()-1);
        buffer.append("]");

        return buffer.toString();
    }
}

这位老哥写得好https://blog.csdn.net/yuan_xw/article/details/104361435

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值