链表环的判断
1 #include <iostream> 2 using namespace std; 3 struct Listnode//定义链表节点 4 { 5 int val; 6 Listnode* next; 7 Listnode(int _val):val(_val),next(nullptr){} 8 } ; 9 //判断链表是否成环 10 bool cycle(Listnode* head) 11 { 12 Listnode* fast=head; 13 Listnode* slow=head; 14 while(fast!=nullptr && fast->next!=nullptr) 15 { 16 slow=slow->next; 17 fast=fast->next->next; 18 if(slow==fast) 19 { 20 21 return true; 22 } 23 } 24 return false; 25 } 26 //判断链表是否存环,存在返回环开始的节点 27 Listnode* cycle_pos(Listnode* head) 28 { 29 Listnode* slow=head; 30 Listnode* fast=head; 31 while(fast!=nullptr && fast->next!=nullptr) 32 { 33 slow=slow->next; 34 fast=fast->next->next; 35 if(slow==fast) 36 { 37 Listnode* index1=fast; 38 Listnode* index2=head; 39 while(index1!=index2) 40 { 41 index1=index1->next; 42 index2=index2->next; 43 } 44 return index1; 45 } 46 } 47 return nullptr; 48 } 49 int main(int argc, char *argv[]) 50 { 51 Listnode* n1=new Listnode(3); 52 Listnode* n2=new Listnode(2); 53 Listnode* n3=new Listnode(0); 54 Listnode* n4=new Listnode(-4); 55 n1->next=n2; 56 n2->next=n3; 57 n3->next=n4; 58 n4->next=n2; 59 cout<<n1->val<<" "<<n2->val<<" "<<n3->val<<" "<<n4->val; 60 bool result=cycle(n1); 61 auto f=[=]{return result?"cycle":"no cycle";}; 62 cout<<f()<<endl;//是否成员 63 Listnode* node=cycle_pos(n1); 64 //auto g=[=]{return node?"cycle":"no cycle";}; 65 //cout<<g()<<endl; 66 if(node) 67 { 68 cout<<"cycle start is:"<<node->val<<endl; 69 } 70 else{ 71 cout<<"no cycle"<<endl; 72 } 73 74 return 0; 75 }