当前位置:网站首页>循环队列的长度「In DataStructure」
循环队列的长度「In DataStructure」
2022-04-21 11:17:00 【东东咚咚东】
看循环队列计算长度公式时对距离的感觉有点模糊,又联想到每次计算两个索引之间的距离都在纠结相减是否要加1。所以写篇博客,以图形角度表现一下两个索引相减的含义,帮助以后计算索引相关问题时不再纠结。
两个索引相减得到的是什么?
对于索引n,如果直接把n减0得到的值是n-0=n,因此我们说索引n与索引0之间有n个值。如下图所示:
推广到数组中间,索引i减去索引j( i>j )得到的值是i-j=i-j,因此我们说索引i到索引j之间有i-j个值。如下图所示:
那么由两个图像的表现可以得到两个索引相减的图形含义:
索引减索引=包含两端索引在内的片段减去尾巴!
验证循环队列的长度公式
规定循环数组头指针指向头元素,尾指针指向尾元素的下一个节点。
那么公式为:(rear - front + QueueSize)% QueueSize 。验证如下:
1.当尾指针索引大于头指针索引
已上图为例,假设头指针为2,尾指针为5。

因此队列长度可以写成 rear - front。
那么公式递推:
rear - front
= (rear - front) % QueueSize <——(rear-front)永远小于队列长度,因此取余还是为原值
= (rear - front) % QueueSize + (QueueSize % QueueSize) <——数对自身取余结果为0
= (rear - front + QueueSize) % QueueSize <——合并
验证成立。
2.当尾指针索引大于头指针索引

见图可得:
rear - front
= - (front - rear)
= 红色线段长度的负数
因此
rear - front + QueueSize
= QueueSize - (front - rear)
= 橙色线段长度
= 队列长度
又 rear - front + QueueSize 小于 QueueSize
所以也可以写成 (rear - front + QueueSize) % QueueSize
所以不管尾指针索引是否大于头指针索引时公式都成立的。
其他情况
第二种队列情况:
头指针指向头元素的前一个节点,尾指针指向尾元素。公式依然成立。
第三种队列情况:
头指针指向头元素,尾指针指向尾元素。公式变为 (rear - front + 1 + QueueSize) % QueueSize
可以自行验证。
版权声明
本文为[东东咚咚东]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Cristiano2000/article/details/124206490
边栏推荐
- (coordinate dynamic programming) lintcode medium 248 · count the number of numbers smaller than a given integer
- 依然AC自动机
- Rhino software plug-in rhino plug-in visual studio create your first plug-in
- Packet life cycle in kubernetes -- Part 1
- How does IOT platform realize business configuration center
- From station B and little red book, how to do a good job of community products?
- [lighthouse] intranet penetration FRP construction
- Realize browser multi tab communication
- AC自动机&后缀数组复习
- New features of ES6 (7): proxy proxy / model module / import / export
猜你喜欢
随机推荐
Teach you to easily solve CSRF Cross Site Request Forgery Attack
Unix哲学与高并发
Dapr 远程调试之 Nocalhost
美国加息人民币贬值,这类产品却迎来蜜月期
Digital IT operation from the perspective of thinking transformation
(coordinate dynamic programming) lintcode medium 248 · count the number of numbers smaller than a given integer
使用 RSA 进行加解密
塔米狗资讯|国资委发言:支持上市公司采用企业并购融资手段拓展主业
make the inifile support unicode in delphi
Suffix array special training
2.精准营销实践阿里云odpscmd数据特征工程.
MATLAB GUI---学科选择(动画演示)
依然AC自动机
MATLAB---选择省份城市应用
省赛练习2——第八届福建省大学生程序设计竞赛 &补题
Why have major apps launched the old version?
便利店卷疯了:便利蜂、罗森、易捷“激战”
Matlab --- progress bar animation demonstration
AC自动机
[lighthouse] intranet penetration FRP construction








