环形链表找入环点----链表OJ---三指针

https://leetcode.cn/problems/linked-list-cycle-ii/description/?envType=study-plan-v2&envId=top-100-liked

首先,需要判断是否有环,而这里我们不单纯判断是否有环,还要为下一步做准备,需要让slow指针和fast都从头结点开始走,实现逻辑就有些不同。

cpp 复制代码
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指针同步移动,去寻找入环点。

cpp 复制代码
//。。。。
if(slow == fast)
{
    struct ListNode* ptr = head;
    while(ptr != slow)
    {
        slow = slow->next;
        ptr = ptr->next;
    }
    return ptr;
}

最后实现代码如下:

cpp 复制代码
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;
}
相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr4 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_34 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.4 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.4 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣4 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9924 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王4 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1014 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质