linked-list - 检测链表中的循环,关于慢速和快速指针
问题描述
我的问题是为什么要检查 slow_ptr 和 fast_ptr 指针是否为 NULL 以查看是否存在循环,而我们只能通过检查 fast_ptr 是否为 NULL 来做到这一点,因为 fast_ptr 的移动速度比 slow_ptr 快。
代码链接:https ://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/
int countNodesinLoop(struct Node *list)
{
struct Node *slow_p = list, *fast_p = list;
//in this part
while (slow_p && fast_p &&
fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet at
some point then there is a loop */
if (slow_p == fast_p)
return countNodes(slow_p);
}
/* Return 0 to indeciate that
their is no loop*/
return 0;
}
解决方案
推荐阅读
- python - Python3 SQLite 行不会在 Ubuntu 上被删除,但会在 Windows 上被删除
- node.js - 如何在 MacOS 上执行节点 js 文件?
- python-3.x - 写入 csv 时出错,不允许我编写 Python3 和 csvwriter
- r - 嵌套循环无法停止
- php - 将 SMTP 添加到 php 表单 Bootstrap
- javascript - 验证来自 javascript ( chrome 控制台) 的角度输入表单
- python - 循环只迭代一次
- python - Python 协程:它们为什么有用?有哪些用例?
- r - 在 ggrepel 标签中使用 plotmath
- leaflet - 为什么此传单折线未显示?