1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 static int wing=[]() 10 { 11 std::ios::sync_with_stdio(false); 12 cin.tie(NULL); 13 return 0; 14 }(); 15 16 class Solution 17 { 18 public: 19 bool hasCycle(ListNode *head) 20 { 21 ListNode *fast=head,*slow=head; 22 while(fast!=NULL) 23 { 24 fast=fast->next; 25 if(fast==NULL) 26 return false; 27 fast=fast->next; 28 slow=slow->next; 29 if(slow==fast) 30 return true; 31 } 32 return false; 33 } 34 };
慢指针追快指针,追到则必有环。
还有一种更简洁的写法
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 static int wing=[]() 10 { 11 std::ios::sync_with_stdio(false); 12 cin.tie(NULL); 13 return 0; 14 }(); 15 16 class Solution 17 { 18 public: 19 bool hasCycle(ListNode *head) 20 { 21 ListNode *fast=head,*slow=head; 22 while(fast!=NULL&&fast->next!=NULL) 23 { 24 fast=fast->next->next; 25 slow=slow->next; 26 if(slow==fast) 27 return true; 28 } 29 return false; 30 } 31 };
浙公网安备 33010602011771号