LeetCode 刷题【142. 环形链表 II】

142. 环形链表 II

自己做

解:三指针

java 复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null)           //必定无环
            return null;
        
        ListNode p = head;
        ListNode q = head.next;
        ListNode r = head.next;

        while(r != null){
            r = r.next;                                 //快指针
            if(r != null)
                r = r.next;

            q = q.next;                                 //慢指针

            if(q == p)                                  //遇到入口
                return p;

            if(r == q)                                  //快指针追上了慢指针(转了一圈)
                p = p.next;

        }   

        //无环
        return null;     
    }
}

看题解

java 复制代码
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast != null) {
            slow = slow.next;
            if (fast.next != null) {
                fast = fast.next.next;
            } else {
                return null;
            }
            if (fast == slow) {
                ListNode ptr = head;
                while (ptr != slow) {
                    ptr = ptr.next;
                    slow = slow.next;
                }
                return ptr;
            }
        }
        return null;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/linked-list-cycle-ii/solutions/441131/huan-xing-lian-biao-ii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
叠层归一研究院1 分钟前
区分预算与通道诱导:Ω–L叠层体系的观测赋值与定量验证
人工智能·算法
BYSJMG23 分钟前
计算机毕业设计选题推荐:基于大数据的快递物流运营数据分析与可视化,Spark与K-Means
大数据·算法·数据分析·spark·课程设计
阳明山水1 小时前
因果一致性正则化实战解析
人工智能·深度学习·算法·机器学习·架构
黄金龙PLUS2 小时前
5个1024比特大状态置换算法的设计与分析
算法·网络安全·密码学·哈希算法·同态加密
心中有你02142 小时前
C语言埃氏筛法(素数筛选)
c语言·数据结构·算法
Omics Pro4 小时前
Cell封面|衰老生物学开源AI工具包
数据库·人工智能·算法·机器学习·自然语言处理
UIU1146 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
用户9799848071811 小时前
200 行代码写一个能跑的 AI Agent:不依赖任何框架,只靠 tool-calling 原理
算法
threerocks11 小时前
【Muse实战】X 流量作战室搭建保姆级教程 - 拥有你自己的运营团队
算法
GreenTea11 小时前
深度拆解 ScienceBuddy:如何用“双层递归自进化”构建高可靠科研 Agent Harness
前端·后端·算法