给定一个单向链表,判断中间是否有环。
bool hasLoop(Node *head)
{
Node *slow = head;
Node *fast = head;
while (slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
return true;
}
}
return false;
}
算法参考:http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare