嗨,我遇到了实现floyds周期检测算法的这段代码,并想知道是否需要检查slow_ptr!=Null
,因为slow_ptr
只遍历那些快速指针遍历或跳过的节点(在检查它是否为非NULL之后,那就是),那么检查if(fast!=Null&&fast->next!=NULL)
是否必要且充分?
这是代码
int detectloop(struct node *list)
{
struct node *slow_p = list, *fast_p = list;
while(slow_p && fast_p &&
fast_p->next )
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
if (slow_p == fast_p)
{
printf("Found Loop");
return 1;
}
}
return 0;
}
答案 0 :(得分:2)
是的,在您发布的代码中slow_p != NULL
检查是多余的。