标签:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL || head->next==NULL)
return NULL;
ListNode * p=head;
ListNode * q=head;
while(q!=NULL&&q->next!=NULL)//第一次pq相遇
{
p=p->next;
q=q->next->next;
if(p==q)
break;
}
if(p==q)
{
p=head;
while(p!=q)//从起点开始,在入口点相遇
{
p=p->next;
q=q->next;
}
return p;
}
return NULL;
}
};
标签:
原文地址:http://www.cnblogs.com/ranranblog/p/5587079.html