数组实现环形队列(JAVA版)

使用了环形队列的方式使得数组空间可以重复利用。

不理解的同学可以用纸画一下,如果有错误的地方希望大家多多指教。

package com.algorithm.queue;

//环形队列实现
public class QueueDemo02 {
    public static void main(String[] args) {

    }
}

//调整:front指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素
//rear指向队列的最后一个元素,因为希望空出一个空间作为约定
//队列满:(rear+1)%maxSize=front
//队列为空:rear == front
class CircleQueue {
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;

    public CircleQueue(int arrMaxSize) {
        maxSize = arrMaxSize;
        arr = new int[maxSize];
    }

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

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

    // 加入数据
    public void add(int x) {
        if (isFull()) {
            System.out.println("队列已经满!");
            return;
        }
        arr[rear] = x;
        rear = (rear + 1) % maxSize;// 假设当前指向3,队列大小为8,那么4%8=4,新指向的位置就为下标4
    }

    // 出队列
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空!");
        }
        // front指向队列的第一个元素
        // 先将front对应的值保存到一个临时变量
        // 将front后移
        // 将临时变量返回
        int tempVal = arr[front];
        front = (front + 1) % maxSize;
        return tempVal;
    }

    // 显示队列中的数据
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空");
            return;
        }
        for (int i = front; i < front + getNum(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    // 求出队列中的有效数据方法
    public int getNum() {
        return (rear + maxSize - front) % maxSize;
    }
    
    //显示头元素
    public int getHead() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return arr[front];
    }
}
 

你可能感兴趣的:(Java数据结构与算法)