您的位置:首页 > 其它

判断链表中是否有环存在

2015-07-10 17:34 323 查看
思路:

用两个指针,pSlow,pFast,就是一个慢一个快

慢的一次跳一步,

快的一次跳两步,

什么时候快的追上慢的了就表示有环(pSlow == pFast )。

实现如下:

struct  listtype
{
int data;
struct listtype * next;
}list;

int find_cicle(list *head)
{
list *pFast=head;
list *pSlow=head;
if (pFast==NULL)
{
return -1;
}
while(pFast && pFast->next)
{
pFast=pFast->next->next;
pSlow=pSlow->next;
if (pFast==pSlow)
{
return 1;
}
}
return 0
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: