判断链表是否有环,且返回环的入口
代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if( head == NULL)
return NULL;
ListNode *fast, *slow;
bool hasCycle = false;
fast = head;
slow = head;
while(fast != nullptr && fast->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
hasCycle = true;
break;
}
}
if(hasCycle)
{
slow = head;
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
else
{
return NULL;
}
}
};