板子題https://leetcode-cn.com/problems/linked-list-cycle/submissions/
又稱快慢指針算法
本算法用來判斷(鏈表)中是否存在環
顯然若烏龜(慢)和兔子(快)在操場上跑步,無論兩者誰先跑、從哪個地方起跑,一定存在某個時刻兔子與烏龜相遇
(邏輯題)
那麼定義兩個指針slow和fast,slow指針一次向後走一步,fast指針一次向後走兩步,若兩指針相遇則鏈表中必定有環
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head == NULL || head->next==NULL)
return false;
struct ListNode *slow=head;
struct ListNode *fast=head->next;
while(slow != fast)
{
if(fast==NULL || fast->next==NULL)
return false;
slow=slow->next;
fast=fast->next->next;
}
return true;
}