思路跟leetcode 287. Find the Duplicate Number一样,都是
用Floyd's Algorithm的龟兔赛跑,不过这里只需要第一次相遇的结果,
第一次相遇就说明有环,如果都到末尾了还不相遇就说明没有环。
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL || head->next->next == NULL) {
return false;
}
ListNode *tortoise = head->next, *hare = head->next->next;
while (tortoise != hare && hare != NULL && hare->next != NULL) {
tortoise = tortoise->next;
hare = hare->next->next;
}
return hare != NULL && hare->next != NULL;
}
};