数据结构笔记-环形队列

package struct.queue;

/**
 * 基于数组实现环形队列
 */
public class CircleQueue {

    private int maxSize;
    private int front;      // 指向队列第一个元素,初始值为 0
    private int back;       // back 指向队列的最后一个元素的后一个位置,空出一个空间作为约定,初始值为 0
    private int[] arr;

    public CircleQueue(int arrMaxSize) {

        maxSize = arrMaxSize;
        arr = new int[maxSize];

    }

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

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

    // 添加元素
    public int addQueue(int n) {

        if(isFull()) {
            return -1;
        }
        arr[back] = n;
        back = (back + 1) % maxSize;//
        return 1;


    }

    // 弹出队列第一个元素
    public int getQueue() {
        if (isEmpty()) {
            return -1;
        }
        int value = arr[front];
        front = (front + 1) % maxSize;  // 只有取模后,队头索引才不会超出
        return value;

    }

    // 返回队列有效数据个数
    public int size() {
        return (back + maxSize - front) % maxSize;
    }

    // 显示队列
    public void show() {
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d
", i, arr[i]);
        }
    }

    // 测试
    public static void main(String[] args) {

        CircleQueue queue = new CircleQueue(3);     // 队列有两个元素

        System.out.println(queue.isFull());
        System.out.println(queue.isEmpty());

        System.out.println(queue.addQueue(7));
        System.out.println(queue.addQueue(8));
        System.out.println(queue.addQueue(9));
        queue.show();

        System.out.println(queue.getQueue());
        queue.show();


    }




}
艺无止境,诚惶诚恐, 感谢开源贡献者的努力!!
原文地址:https://www.cnblogs.com/d0usr/p/12448732.html