Given a linked list, determine if it has a cycle in it.
分析:经典面试题,用二个指针,一个每次走一步,一个每次走两步,走二步的遇到走一步的便是有环,走两步的走到NULL便是无环
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *one;
ListNode *two;
if(head == NULL)return false;
else one = head->next;
if(one == NULL)return false;
else two = one->next;
if(two == NULL)return false;
while(1)
{
for(int i = 0; i < 2; i++)
{
two = two->next;
if(two == NULL)return false;
else if(two == one)return true;
}
one = one->next;
}
}
};