题目描述:
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?
思路:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head) return NULL;
ListNode *p = head;
ListNode *q = head;
do{
if(!p||!q) return NULL;
p = p->next;
q = q->next;
if(q) q = q->next;
else return NULL;
}while(p!=q);
p = head;
while(p!=q){
p = p->next;
q = q->next;
}
return p;
}
};
LeetCode 142: Linked List Cycle II
原文:http://www.cnblogs.com/xiamaogeng/p/4415257.html