我不太了解队列上的这个算法
I don't quite understand this algorithm on queue
以下是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。
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 为什么这个运算符<重载函数对 STL 算法不可见?
- Android NDK传感器向事件队列报告奇怪的间隔
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 优先级队列和 Prim 算法
- 利用优先级队列C++优化了从O(n^2)到O(n)的Huffman树算法
- 我不太了解队列上的这个算法
- boost::基于线程的队列算法
- 为什么我的基本优先级队列排序算法会导致 seg 错误
- 创建"relative"优先级队列的算法?(C/C++)
- 具有优先级队列的Dijkstras算法
- Dijkstra算法中的优先级队列
- 为什么在 Prim 算法中我们需要优先级队列
- 对最短路径算法进行建模时的队列问题
- 我应该对 dikjstra/A* 算法使用可变优先级队列吗?
- dijkstra算法在基于堆的优先级队列中的查找时间