当前位置:   article > 正文

快慢指针判断链表是否有环_使用快慢指针判断单链表是否有环

使用快慢指针判断单链表是否有环

原来的代码判断是否有环比较的是快慢指针是否有朝一日指向的节点的值相同,

而这是有漏洞的,当输入的节点值有重复时,也可能使代码作出有环的误判,现修改其判断指标为当两个指针的地址相同时,则有环。

然而快慢指针缺点略大,两指针极易错过,当环巨大时,耗费过多的时间,也许存在优化的可能,改天再写吧。。。

  1. int hasloop(linklist l)//快慢指针判断是否有环
  2. {
  3. node *p1,*p2;
  4. if(l == NULL || l->next == NULL) //链表为空,或是单结点链表直接返回头结点
  5. return 0;
  6. p1 = p2 = l;
  7. while(p2->next != NULL && p1->next->next != NULL)
  8. {
  9. p1 = p1->next->next;
  10. p2 = p2->next;
  11. if(p1->data == p2->data)
  12. return 1;
  13. }
  14. return 0;
  15. }

修改后整题代码如下:
实例:建立一个链表,判断是否存在环
 

  1. #include "stdafx.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <malloc.h>
  5. #include <string.h>
  6. typedef struct node
  7. {
  8. char data;
  9. struct node *next;
  10. }node, *linklist;
  11. void initlist(linklist *l)
  12. {
  13. *l = (linklist)malloc(sizeof(node));
  14. (*l)->next=NULL;
  15. }
  16. void creatfromhead(linklist l)
  17. {
  18. node *s;
  19. char c;
  20. int flag = 1;
  21. while(flag)
  22. {
  23. c = getchar();
  24. if(c != '#')
  25. {
  26. s=(node*)malloc(sizeof(node));
  27. s->data=c;
  28. s->next = l->next;
  29. l->next = s;
  30. }
  31. else
  32. flag=0;
  33. }
  34. }
  35. int hasLoop(linklist l)//快慢指针判断是否有环
  36. {
  37. node *p1,*p2;
  38. if(l == NULL || l->next == NULL) //链表为空,或是单结点链表直接返回头结点
  39. return 0;
  40. p1 = p2 = l;
  41. while(p2->next != NULL && p1->next->next != NULL)
  42. {
  43. p1 = p1->next->next;
  44. p2 = p2->next;
  45. if(p1== p2)
  46. return 1;
  47. }
  48. return 0;
  49. }
  50. int main(int argc, char* argv[])
  51. {
  52. linklist l;
  53. initlist(&l);
  54. creatfromhead(l);
  55. if(hasLoop(l))
  56. printf("有环\n");
  57. else
  58. printf("无环\n");
  59. return 0;
  60. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/895337
推荐阅读
相关标签
  

闽ICP备14008679号