追逐法檢測單鏈表中的環

 追逐法檢測單鏈表中的環,不知道還有沒有更高效的算法?歡迎拍磚!

  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 }
發佈了15 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章