关于java中使用循环数组的队列数据结构

关于java中使用循环数组的队列数据结构,java,Java,这项任务 public class Queue { private int [] queue ; // here we define an array for queue private int size , rear ,front; // it's size front and rear private static final int CAP = 15; // default capacity public Queue(int cap){

这项任务

public class Queue {

    private int [] queue ; // here we define an array for queue
    private int size , rear ,front; // it's size front and rear 
    private static final int CAP = 15; // default capacity


    public Queue(int cap){

        queue = new int[cap];
        size = 0;
        front = 0;
        rear = 0;

    }// end of Queue 


    public void enQueue(int data){

        if(size == CAP) // size of queue is full 
            System.out.println("Queue is full");

        else{

            size++; // first we increment the size because it's zero
            queue[rear] = data;// and add data to rear of circular array
            rear = ( rear + 1 ) % CAP; 
    /* **but here i don't know this line of code could some one please help me here **

    i don't know why here they take % of ( rear + 1 ) of circular array
    ---------------------------------------------------------
    */

        } // end of else 

}// end of enQueue
向后推进1,如果到达上限,则使用单个表达式将其降回零。您可以使用两个操作重写此文件:

rear = ( rear + 1 ) % CAP;
%是模算子。当rear+1位于CAP下方时,您将获得rear+1。一旦后+1达到上限,模产生零


使用条件式阅读不需要任何先验知识。然而,一旦你知道了模运算技巧,它也就变得容易理解了。

%modulo操作会提醒你这个操作。 在这里,rear将被分配一个始终小于容量的值。
因此,为了确保此处使用的%是使用循环数组实现的队列。开始添加元素时,应移动到下一个单元格,在该单元格中添加下一个元素

如果您的容量为15,那么如果将运算符%应用于0到14之间的数字,则得到的是相同的数字

rear++;
if (rear == CAP) {
    rear = 0;
}
但是,在某些情况下,您应该回到数组的开头。如果不这样做,您将获得ArrayIndexOutOfBoundsException。那么


你总是在前面排队,在后面排队。循环队列的性质是,它会环绕。如果您有7个插槽,则第8个插槽是0开头。如果你回到前面,那就满了。前面和后面的索引/指针都会移动,因为当您将前面的移动和后面的移动排成队列时

您的代码试图通过使用模运算符来解决超出上限的问题。也就是说,它只是不断地环绕着后部,同时允许后部的实际值不断增加。如果没有任何绑定检查,这将永远覆盖

例如。 如果后=14,则后+1=15 后部+1%封顶->14+1%封顶->15%15=0

此链接可能对您有用:
^如果这是一个类的代码,建议您在查看代码之前再试一次。否则,请查看第一张图片,然后跳到代码以便更好地理解。

您知道%operator的作用吗?在逻辑圆形阵列中,当前进将使您越过物理线性阵列的末端时,您需要做什么?可能的重复请参见:@Maseeh.Niazai欢迎您。由于问题已解决,请考虑通过点击左边的灰色复选标记来接受答案。这将为您赢得一个新的堆栈溢出徽章。
2 % 15 --> 2

14 % 15 --> 14
15 % 15 --> 0