一、代码实现

public class CircularArrayQueue {
    /**
     * 队列最大容量
     */
    private int maxSize;
    /**
     * 队列头指针(指向首元素)
     */
    private int front;
    /**
     * 队列尾指针(指向尾元素的后一个位置)
     */
    private int rear;
    /**
     * 数组模拟队列容器
     */
    private int[] arr;

    /**
     * 初始化循环队列
     * @param maxSize int
     */
    public CircularArrayQueue(int maxSize){
        this.maxSize = maxSize;
        arr = new int[maxSize];
        rear = front = 0;
    }

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

    /**
     * 判断队列是否为空
     * @return isEmpty boolean
     */
    public boolean isEmpty(){
        return rear==front;
    }

    /**
     * 入队列
     * @param n 元素值
     */
    public void addQueue(int n){
        //队满不能入队
        if(isFull()){
            throw new RuntimeException("队列已满,无法加入数据!");
        }
        arr[rear] = n;
        rear = (rear+1)%maxSize;
    }

    /**
     * 出队列
     * @return int
     */
    public int getQueue(){
        //队空不能出队
        if(isEmpty()){
            throw new RuntimeException("队列已空,无法取得数据!");
        }
        int value = arr[front];
        front = (front+1)%maxSize;
        return value;
    }

    /**
     * 遍历队列所有元素
     */
    public void showQueue(){
        if(isEmpty()){
            System.out.println("队列为空!");
        }
        for (int i = front; i < front + size(); i++) {
            System.out.println(arr[i%maxSize] + "\t");
        }
    }

    /**
     * 获取当前队列元素个数
     * @return size int
     */
    public int size(){
        return (rear-front+maxSize)%maxSize;
    }

    /**
     * 获取队首元素
     * @return
     */
    public int headQueue(){
        if(isEmpty()){
            throw new RuntimeException("队列已空,无法取得数据!");
        }
        return arr[front];
    }
}

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/wN4eqwrOE/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息