思路
定义两个指针(快指针 f 和慢指针 s )同时指向链表头结点,循环地让块指针走两步(f=f->next->next)慢指针走一步(s=s->next),当快指针指向节点和该节点的next不为空时,判断两个指针是否相遇(f=s),相遇则返回真。
代码
/**
* 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)
return false;
int pos=-1;
ListNode *p=head;
ListNode *f=head;
ListNode *s=head;
while(f&&f->next)
{
f=f->next->next;
s=s->next;
if(s==f)
{
for(pos=-1;p!=f->next;pos++)
{
p=p->next;
}
pos++;
return true;
}
}
return false;
}
};