Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
bool hasCycle(ListNode *head)
{
<span style="white-space:pre"> </span>if(head == NULL)
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>ListNode* pslow = head;
<span style="white-space:pre"> </span>ListNode* pfast = head;
<span style="white-space:pre"> </span>while(pfast != NULL && pfast ->next != NULL)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>pslow = pslow->next;
<span style="white-space:pre"> </span>pfast = pfast->next->next;
<span style="white-space:pre"> </span>if(pfast == pslow)
<span style="white-space:pre"> </span>return true;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return false;
}
分析:用到了快慢指针。如果快指针追上了慢指针,说明存在循环,否则没有。
已AC 76ms