求链表环的起始位置

leetcode中题目位置

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

代码:

java 复制代码
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        // a + b = slow = cnt;
        // a + b + (b + c)x = fast = 2 * slow = 2cnt ----> bx+cx = cnt
        // a = b(x-1) + cx = (b + c)(x - 1) + c, 即从 相遇节点、root节点出发,经过(a+1)节点后,他们会在头结点相遇;
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast.next == null || fast.next.next == null) {
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        slow = slow.next;
        while (head != slow) {
            head = head.next;
            slow = slow.next;
        }
        return head;
    }
}

重点:快慢指针相遇后,慢指针继续往前,同时root也开始往前(root.next = head), 他们必然会相遇,即a = (b + c)(x - 1) + c

* a+1是root到环起点的步数;

* c+1是慢指针从相遇节点 到 环起点的步数;

* b+c是环的节点数

相关推荐
英英_11 小时前
MATLAB数值计算基础教程
数据结构·算法·matlab
程序员-King.13 小时前
day143—递归—对称二叉树(LeetCode-101)
数据结构·算法·leetcode·二叉树·递归
仙俊红16 小时前
LeetCode174双周赛T3
数据结构·算法
仍然.17 小时前
JavaDataStructure---二叉搜索树,哈希表,Map和Set
数据结构·散列表
程序员-King.18 小时前
链表——算法总结与新手教学指南
数据结构·算法·链表
FMRbpm18 小时前
树的练习6--------938.二叉搜索树的范围和
数据结构·c++·算法·leetcode·职场和发展·新手入门
多米Domi01119 小时前
0x3f 第35天 电脑硬盘坏了 +二叉树直径,将有序数组转换为二叉搜索树
java·数据结构·python·算法·leetcode·链表
凯子坚持 c21 小时前
C++大模型SDK开发实录(一):spdlog日志封装、通用数据结构定义与策略模式应用
数据结构·c++·sdk·策略模式
漫随流水21 小时前
leetcode算法(513.找树左下角的值)
数据结构·算法·leetcode·二叉树
全栈游侠21 小时前
数据结构 -数组
数据结构