追逐法检测单链表中的环

 追逐法检测单链表中的环,不知道还有没有更高效的算法?欢迎拍砖!

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <stdbool.h>
  4
  5 typedef struct linklist{
  6     int data;
  7     struct linklist *next;
  8 }linklist;
  9
 10 bool check_loop(linklist *pHead)
 11 {
 12     if (0 == pHead)
 13         return false;
 14
 15     linklist *pFast = pHead, *pSlow = pHead;
 16
 17     while(0 != pFast)
 18     {
 19         pFast = pFast->next;
 20         pSlow = pSlow->next;
 21         if (0 != pFast){
 22             pFast = pFast->next;
 23             if (pFast == pSlow)
 24                 return true;
 25         }
 26     }
 27     return false;
 28 }
 29
 30 int main()
 31 {
 32     linklist pHead;
 33     linklist *q = 0;
 34     int i;
 35     for(i = 0; i < 10; i++)
 36     {
 37         linklist *p = malloc(sizeof(linklist));
 38         p->data = i;
 39         p->next = 0;
 40         if (9 == i)
 41             p->next = pHead.next;
 42
 43         if (0 == q)
 44             pHead.next = p;
 45         else
 46             q->next = p;
 47
 48         q = p;
 49     }
 50
 51     if(check_loop(&pHead))
 52         printf("There is a loop in the linked lisst./n");
 53     else
 54         printf("No loop/n");
 55
 56     return 0;
 57 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值