Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路很简单:利用快慢指针,开始两个指针均指向链表head,然后循环移动,慢指针移动1步,快指针则移动2步,如果链表有环则两个指针一定会相遇。
<span style="font-size:18px;">bool hasCycle(ListNode *head)
{
if(head==NULL||head->next==NULL)
return false;
ListNode *fast=head,*slow=head;
while(fast&&fast->next)//这里不用担心会出现死循环,因为要么有环,要么没有。
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}</span>