英文命题:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
`/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
解析:快慢指针法,一个每次前进一步,一个每次前进两步,当他们到达尾节点前,他们的值相等,标志着链表中有环。
代码:
bool hasCycle(ListNode *head)
{
if (!head)
{
return false;
}
ListNode * slow=head;
ListNode * fast=head;
//注意这里需要三个判断条件
while (slow->next && fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
return true;
}
}
return false;
}