判断一个链表是否为循环单链表:
#设置两个指针(fast, slow),slow步长为1,fast步长为2,
大概的思路如下:
如果链表为循环单链表,则fast与slow必定相遇。
如果链表不为循环单链表,则fast必定先指向NULL。
int IsLoopList(list *head)
{
list *s = head->next; //慢指针
list *f = head->next->next; //快指针
if ((NULL == head) || (NULL == head->next))
{
return -1;
}
while ((s != NULL) && (f != NULL) && (f->next != NULL))
{
if (s == f)
{
return 0; //是循环单链表
}
s = s->next;
f = f->next->next;
}
return -1;
}