https://leetcode.cn/problems/linked-list-cycle-ii/description/?envType=study-plan-v2&envId=top-100-liked
首先,需要判断是否有环,而这里我们不单纯判断是否有环,还要为下一步做准备,需要让slow指针和fast都从头结点开始走,实现逻辑就有些不同。
struct ListNode* slow = head,*fast = head;
while(fast != NULL)//如果fast为空,说明不会有环
{
if(fast == NULL || fast->next == NULL)
return NULL;
//注意这里,||两边交换位置是会出现错误的,如果交换位置,当fast == NULL时,if语句是先判断第一个条件,那么此时会空指针进行了解引用,程序崩溃
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
//....找到交点,也代表有环
}
找到交点后,我们就要引入ptr指针,来和slow指针同步移动,去寻找入环点。
//。。。。
if(slow == fast)
{
struct ListNode* ptr = head;
while(ptr != slow)
{
slow = slow->next;
ptr = ptr->next;
}
return ptr;
}
最后实现代码如下:
struct ListNode *detectCycle(struct ListNode *head)
{
struct ListNode* slow=head,*fast = head,*ptr = head;
while(fast != NULL)
{
if(fast==NULL || fast->next == NULL)
return NULL;
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
while(ptr != slow)
{
ptr= ptr->next;
slow = slow->next;
}
return ptr;
}
}
return NULL;
}