思路跟leetcode 287. Find the Duplicate Number,
leetcode 141. Linked List Cycle一样,都是用Floyd's Algorithm
的龟兔赛跑解决,这里与141题对比还需要第二次相遇的结果,
第一次相遇就说明有环,如果都到末尾了还不相遇就说明没有环。第二次
相遇的节点就是环的起点。
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 || head->next->next == NULL) {
return NULL;
}
ListNode *tortoise = head->next, *hare = head->next->next;
while (tortoise != hare && hare != NULL && hare->next != NULL) {
tortoise = tortoise->next;
hare = hare->next->next;
}
if (hare != NULL && hare->next != NULL) {
return NULL;
}
tortoise = head->next;
hare = hare->next;
while (tortoise != hare) {
tortoise = tortoise->next;
hare = hare->next;
}
return tortoise;
}
};