Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
解题思路:http://xingxjhui.blog.163.com/blog/static/2155451642014013154023/
/**
* 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) return NULL;//空结点
ListNode *p=head,*q=head;
while(p && q){
p=p->next;
if(q->next==NULL) return NULL;
q=q->next->next;
if(p==q) break;
}
if(p==NULL || q==NULL ){
return NULL;
}
p=head;
while(p!=q){
p=p->next;
q=q->next;
}
return p;
}
};