【发布时间】:2021-09-02 12:00:08
【问题描述】:
我写了一个简单的算法来检测单链表中的循环,它对循环列表正常工作。但是对于没有循环的列表,执行while循环后,printf函数不会在给定代码的最后一条语句中打印。
这是代码的一部分:-
//Detacting a loop in singally linked list Using Fast(2x) and Slow (1x) traversal;
void DetactLoop(struct Node **head)
{
struct Node *Fast = *head;
struct Node *Slow = *head;
if (Fast == NULL)
{
printf("Head is NULL");
return;
}
while (Fast != NULL || Fast->next != NULL)
{
Fast = Fast->next->next;
Slow = Slow->next;
if (Fast == Slow)
{
printf("Loop detected!");
return;
}
}
printf("No Loop found!");
}
【问题讨论】:
标签: c linked-list