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

时间:2018-01-22 19:29:00

标签: 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){

        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

4 个答案:

答案 0 :(得分:1)

此作业

rear = ( rear + 1 ) % CAP;

rear提前一个,如果使用单个表达式到达CAP,则将其降回零。您可以使用两个操作重写它:

rear++;
if (rear == CAP) {
    rear = 0;
}

%是模运算符。当rear + 1位于CAP之下时,您会获得rear + 1。一旦rear + 1达到CAP,模数就会生成零。

使用条件不需要先前的知识来阅读。但是,一旦你知道模数技巧,它也会变得容易理解。

答案 1 :(得分:0)

%(Modulo)操作提供操作提醒。 在这里,后方将被赋予一个始终小于容量的值。 所以要确保在这里使用%

答案 2 :(得分:0)

您正在使用循环数组实现队列。当您开始添加元素时,您应该移动到下一个单元格,其中将添加下一个元素。

如果您的容量为15,那么如果您将运营商%提供给0到14之间的数字,那么您获得的数字就是相同的数字。

2 % 15 --> 2

14 % 15 --> 14

但是,在某些时候你应该回到数组的开头。如果你不这样做,你将获得ArrayIndexOutOfBoundsException。然后,

15 % 15 --> 0

答案 3 :(得分:0)

你总是在前面出列,然后在后排列。 循环队列的性质是它包裹的。如果你有7个插槽,那么"第8个插槽"是0(开头)。如果你回到前面那么它已经满了。前后索引/指针都会移动,因为当您将前移动排队并将后排移动排队时。

您所拥有的代码正试图通过使用模数运算符来解决超出CAP的问题。也就是说它只是保持后部缠绕,同时允许后部的实际值继续增加。没有任何约束检查,这将永远覆盖。

  

E.g。
  如果后方= 14则后方+ 1 = 15
  (后+ 1)%CAP - > (14 + 1)%CAP - > (15)%15 = 0

此链接可能对您有用:
https://www.geeksforgeeks.org/circular-queue-set-1-introduction-array-implementation/
^建议你在查看它显示的代码之前有另一个去,如果这是一个类。否则,请查看第一张图片,然后跳到代码中以便更好地理解。