简体   繁体   English

我对队列中的这个算法不太了解

[英]I don't quite understand this algorithm on queue

Here's the queue using array implementation in Robert Sedgewick's book: 这是Robert Sedgewick的书中使用数组实现的队列:

class QUEUE {
private:
    int* q;
    int N;
    int head;
    int tail;
public:
    QUEUE(int maxN) {
        q = new int[maxN + 1];
        N = maxN + 1; head = N; tail = 0;
    }
    int empty() const {
        return head % N == tail;
    }
    void put(int item) {
        q[tail++] = item; tail = tail % N;
    }
    int get() {
        head = head % N; return q[head++];
    }
};

My concern is about the get() method. 我关心的是get()方法。 Consider the size to be 10; 考虑大小为10; According to the code, initially, the index of head = 11 and index of tail = 0. 根据代码,最初,head的索引为11,tail的索引为0。

Now, add an element, say 1. So, 1 is placed in the index position 0 and the tail position is incremented to 1. Now add another say 5. 5 is at index pos 1 and the tail now is index 2. 现在,添加一个元素,例如1。因此,将1放置在索引位置0并将尾部位置递增到1。现在添加另一个说法5。5在索引pos 1处,而尾部现在是索引2。

Now use the get() function, which does: return q[head++]; 现在使用get()函数,该函数执行以下操作: return q[head++]; which is to return the element at head and then increment the head but BOOOOOM!!!!! 这是返回元素在head,然后增加head但是BOOOOOM !!!! The head is index no 11 as we have just seen and it has no value stored in it and this must be a huge error. 正如我们刚刚看到的那样,磁头是索引号11,它没有存储任何值,这肯定是一个巨大的错误。 But, this code is correct as it's Robert Sedgewick and we are the one's mistaken. 但是,此代码是正确的,因为它是Robert Sedgewick,而我们是一个错误的人。 What's going on guys? 伙计们怎么了? :( :(

You are missing out the ` 您错过了`

head = head % n; // this mean head is now the remainder of the division 
                 // between head and N`

It means head is no longer 10; 这意味着head不再是10;

head = 11 % 11 
which is 0 as the remainder of this division is zero.
Therefore, head = 0;

Then when you return q[head++], you are returning q[0] and then you are setting head to 1. 然后,当您返回q [head ++]时,您将返回q [0],然后将head设置为1。

If you create a queue with size 10 then head equals 10. In get we use 如果您创建一个大小为10的队列,那么head等于10。

head = head % N;
head = 10   % 10
head = 0

So head is 0 and then we increment it to 1. 因此head为0,然后将其递增为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM