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

I don't quite understand this algorithm on queue

本文关键字:算法 队列 了解      更新时间:2023-10-16

以下是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++];
    }
};

我关心的是get()方法。将大小考虑为10;根据代码,最初,头部的索引=11,尾部的索引=0。

现在,添加一个元素,比如1。因此,1被放置在索引位置0,尾部位置被递增到1。现在再加一个,比如5。5在索引位置1,而尾部现在是索引2。

现在使用get()函数,它执行:return q[head++];,返回head处的元素,然后递增head,但BOOOOM!!!!!正如我们刚刚看到的,头是11号索引,其中没有存储任何值,这一定是一个巨大的错误。但是,这个代码是正确的,因为它是Robert Sedgewick,而我们错了。怎么了,伙计们?:(

如果创建一个大小为10的队列,则head等于10。在get中,我们使用

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

所以head是0,然后我们把它增加到1。

您错过了`

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

这意味着头不再是10;

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

然后,当您返回q[head++]时,您将返回q[0],然后将head设置为1。