您的位置:首页 > 其它

判断一个单向链表中是否有环

2012-11-03 19:49 225 查看

写一段代码判断一个单向链表中是否有环

思路:
用两个指针,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}
调用函数返回值为1时,表示单向链表有环;调用函数返回值为-1时,表示测试的单向链表为空;[/code]
调用函数返回值为0时,表示单向链表无环;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: