思路跟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;
}
};
本文介绍了一种使用Floyd's Algorithm来检测链表中是否存在环的方法。通过定义快慢两个指针,快指针每次移动两步,慢指针每次移动一步,如果两者相遇则表明链表有环。
799

被折叠的 条评论
为什么被折叠?



