Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断单链表中是否有环存在。
设置两个指针,slow和fast,slow每次前进一个节点,fast每次前进两个节点,两个指针从头结点同时出发,若链表中存在环,fast必然会追上slow指针,在两指针相同时返回true即可,若指针到达链表结尾,必然无环,返回false。
AC code:
/**
* 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||head->next==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;
}
};