有環單鏈表

有環單鏈表需要解決的問題:

1、如何判斷有環沒有環?

使用追趕的方法,設定兩個指針slow、fast,從頭指針開始,每次分別前進1步、2步。如存在環,則兩者相遇;如不存在環,fast遇到NULL退出。

2、如何判斷環的長度?

記錄下問題1的碰撞點p,slow、fast從該點開始,再次碰撞slow所走過的操作數就是環的長度s

3、如何找到環的連接點在哪裏?

有定理:碰撞點p到連接點的距離=頭指針到連接點的距離,因此,分別從碰撞點、頭指針開始走,相遇的那個點就是連接點。

4、如何求帶環單鏈表的長度?

問題3中已經求出連接點距離頭指針的長度,加上問題2中求出的環的長度,二者之和就是帶環單鏈表的長度

  1. #include<iostream>  
  2. using namespace std;  
  3. struct Node  
  4. {  
  5.     int data;  
  6.     Node *next;  
  7. };  
  8.  
  9. //判斷是否有環  
  10. Node* CircleExist(Node *head)  
  11. {  
  12.     Node *slow=head;  
  13.     Node *fast=head;  
  14.     while(fast!=NULL&&fast->next!=NULL)  
  15.     {  
  16.         slow=slow->next;  
  17.         fast=fast->next->next;  
  18.         if(slow==fast)  
  19.             return slow;  
  20.     }  
  21.     return NULL;  
  22. }  
  23.  
  24. //得到環的長度  
  25. int GetCircleLength(Node *slow)  
  26. {  
  27.     int length=1;  
  28.     Node *fast=slow;  
  29.     slow=slow->next;  
  30.     fast=fast->next->next;  
  31.     while(fast!=slow)  
  32.     {  
  33.         slow=slow->next;  
  34.         fast=fast->next->next;  
  35.         length++;  
  36.     }  
  37.       
  38.     return length;  
  39. }  
  40. //得到環的連接點  
  41. int GetConnectPoint(Node *head,Node *slow,int &count)  
  42. {  
  43.     count=0;  
  44.     while(head!=slow)  
  45.     {  
  46.         head=head->next;  
  47.         slow=slow->next;  
  48.         count++;  
  49.     }  
  50.     return slow->data;  
  51. }  
  52. void main()  
  53. {  
  54.     Node list[8];  
  55.     for(int i=0;i<8;i++)  
  56.         list[i].data=i;  
  57.     list[0].next=&list[1];  
  58.     list[1].next=&list[2];  
  59.     list[2].next=&list[3];  
  60.     list[3].next=&list[4];  
  61.     list[4].next=&list[5];  
  62.     list[5].next=&list[6];  
  63.     list[6].next=&list[7];  
  64.     list[7].next=&list[2];  
  65.     Node *c=CircleExist(&list[0]);  
  66.     if(c!=NULL)  
  67.         cout<<"有環!\n";  
  68.     else 
  69.     {  
  70.         cout<<"無環!\n";  
  71.         return;  
  72.     }  
  73.     int circlelength=GetCircleLength(c);  
  74.     cout<<"環的長度:"<<circlelength<<endl;  
  75.     int count=0;  
  76.     cout<<"環的連接點:"<<GetConnectPoint(&list[0],c,count)<<endl;  
  77.     cout<<"鏈表總長度:"<<count+circlelength<<endl;  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章