Linked List 檢測 cycle,使用 Floyd’s Cycle detection(龜兔賽跑) 方式
-烏龜每次走一格
-兔子每次走兩格
-烏龜兔子相遇(true);碰到尾(false)
reference:https://hackmd.io/@sysprog/c-linked-list
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL){
return false;
}
ListNode *fast = head, *slow = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};