單鏈表是否有環,環的大小,第一個連接點,有環的單鏈表長度

給定一個單鏈表,只給出頭指針h:
1、如何判斷是否存在環?
2、如何知道環的長度?
3、如何找出環的連接點在哪裏?
4、帶環鏈表的長度是多少?
下面是實現,可以相互檢查一下是否不正確。

/*
  2     Here we discuss four question about single list
  3     1. isCircle(ListNode* head)
  4     2. lenghtOfCircle_list(ListNode* head)
  5     3. firstNodeOfCircle(ListNode* head)
  6     4. lengthOfCircle(ListNode* head);
  7 */
  8 struct ListNode{
  9     int val;
 10     ListNode* next;
 11 };
 12 bool isCircle(ListNode* head){
 13 
 14     if(head==NULL)
 15         return false;
 16     ListNode* slow=head;
 17     ListNode* fast=head;
 18     while(fast!=NULL){
 19         slow=slow->next;
 20         if(fast->next!=NULL)
 21             fast = fast->next->next;
 22         if(slow==fast)
 23             return true;
 24     }
 25     return false;
 26 }
 27 int lengthOfCircle(ListNode* head){
 28     if(head==NULL)
 29         return 0;
 30     int result=0;
 31     ListNode* slow=head;
 32     ListNode* fast=head;
 33     while(fast!=NULL){
 34         slow=slow->next;
 35         if(fast->next!=NULL)
 36             fast = fast->next->next;
 37         if(slow==fast){
 38           //conflict node,
 39             result++;
 40             slow=slow->next;
 41             fast=fast->next->next;
 42             while(slow!=fast){
 43                 slow=slow->next;
 44                 fast=fast->next->next;
 45                 result++;
 46             }
 47             return result;
 48         }
 49     }
 50     return result;
 51 }
 52 ListNode* firstNodeOfCircle(ListNode* head){
 53     if(head==NULL)
 54         return 0;
 55     int result=0;
 56     ListNode* slow=head;
 57     ListNode* fast=head;
 58     while(fast!=NULL){
 59         slow=slow->next;
 60         if(fast->next!=NULL)
 61             fast = fast->next->next;
 62         if(slow==fast){
 63           //conflict node,
 64             while(slow!=head){
 65                 slow=slow->next;
 66                 head=head->next;
 67             }
 68             return head;
 69         }
 70     }
 71     return NULL;
 72 
 73 }
 74 int lenghtOfCircle_list(ListNode* head){
 75     if(head==NULL)
 76         return 0;
 77     int result=lengthOfCircle(head);
 78     if(result==0){
 79         //no circle
 80         ListNode* node=head;
 81         int res=0;
 82         while(node!=NULL){
 83             node=node->next;
 84             ++res;
 85         }
 86         return res;
 87     }
 88     ListNode* temp=firstNodeOfCircle(head);
 89     ListNode* node=head;
 90     int res=0;
 91     while(temp!=node){
 92         res++;
 93         node = node->next;
 94     }
 95     return res+lengthOfCircle(head);
 96 }
發佈了77 篇原創文章 · 獲贊 23 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章