标签:
思路:龟兔赛跑,一个指针兔跑得快,一个指针龟跑得慢,如果有环兔子一定会遇到乌龟(fast == slow),如果没有环兔子一定能到达终点(fast == null)
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head)
{
ListNode* fast = head;
ListNode* slow = head;
while (fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (fast == NULL )
{
return false;
}
if (fast == slow)
{
return true;
}
}
}
return false;
}
};
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/c4f1d6d27435e57f32e0d72c30a59803.html