使用快慢指针,在环形链表内部,快指针迟早会追上慢指针。
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;
}