这道题采用的比较典型的龟兔赛跑的思想,用更快的兔子套乌龟,如果存在环的话就会在兔子最终会抓到乌龟的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *step_one = head;
ListNode *step_two = head;
while(step_two != NULL && step_two->next != NULL && step_two->next->next != NULL)
{
step_one = step_one->next;
step_two = step_two->next->next;
if(step_one == step_two)
return true;
}
return false;
}
};