使用快慢指針,在環形鏈表內部,快指針遲早會追上慢指針。
bool hasCycle(struct ListNode *head)
{
if(head == NULL || head->next == NULL)
return false;
struct ListNode *fast = head->next; //fast = head將不能進入循環
struct ListNode *slow = head;
while(fast != head){
if(fast == NULL || fast->next == NULL)//判斷爲非環形鏈表
return false;
fast = fast->next->next;
slow = slow->next;
}
return true;
}