队列三 数组模拟循环队列

package com.hao.firstdemo.datastruct;

/**
 * @author haoxiansheng
 */
public class TestCircleArry {
    public static void main(String[] args) {
        //测试代码自己可以实现
        CircleArray circleArray = new CircleArray(7);
        circleArray.addQueue(5);
        circleArray.show();
    }
}

class CircleArray {
    private int maxSize; //表示数组的最大容量

    /**
     * 指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素 初始值 front = 0
     * 队列头部
     */
    private int front;

    /**
     * 指向最后一个元素的后一个位置,希望空出一个空间做约定。初始值 rear = 0
     * 队列尾部
     */
    private int rear;
    private int[] arr; //存放数据

    /**
     * 创建队列构造器
     * front rear 默认为0
     *
     * @param arryMaxSize
     */
    public CircleArray(int arryMaxSize) {
        maxSize = arryMaxSize;
        arr = new int[maxSize];
    }

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

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

    /**
     * 添加数据
     *
     * @param n
     */
    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("队列已满不能添加数据");
            return;
        }
        //添加数据
        arr[rear] = n;
        //指针后移 取模
        rear = (rear + 1) % maxSize;
    }

    /**
     * 获取队列数据 出队
     *
     * @return
     */
    public int popQueue() {
        if (isEmpty()) {
            System.out.println("队列中不存在数据");
            throw new RuntimeException("队列为空,不能取数据");
        }

        /**
         * 1、先将数据保存到一个零时变量中
         * 2、front 后移
         * 3、将零时变量返回
         */
        int temp = arr[front];
        front = (front + 1) % maxSize;
        return temp;
    }

    /**
     * 显示数据
     */
    public void show() {
        if (isEmpty()) {
            System.out.println("队列中没有数据");
        }
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d", i % maxSize, arr[i % maxSize]);
        }
    }

    /**
     * 求出队列中数据的有效个数
     *
     * @return
     */
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    /**
     * 显示队列的头数据
     *
     * @return
     */
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空的没有数据");
        }
        return arr[front];
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值