求链表环的起始位置

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是环的节点数

相关推荐
jiushiapwojdap12 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
纽扣66713 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
xvhao201315 小时前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法
m0_6294947317 小时前
LeetCode 热题 100-----17.缺失的第一个正数
数据结构·算法·leetcode
hnjzsyjyj18 小时前
洛谷 P1443:马的遍历 ← BFS
数据结构·bfs
做时间的朋友。18 小时前
精准核酸检测
java·数据结构·算法
如君愿19 小时前
考研复习 Day28 | 习题--计算机网络第四章(网络层 中)、数据结构(树与二叉树 下)
数据结构·计算机网络·考研·课后习题·记录考研
江南十四行19 小时前
排序算法进阶:直接插入排序(简单排序)与希尔排序
数据结构·算法·排序算法
洛水水19 小时前
【Redis入门】一篇详解Redis五大数据结构
数据结构·数据库·redis
CoderCodingNo19 小时前
【CSP】CSP-J 2021真题 | 插入排序 luogu-P7910 (适合GESP四-六级及以上考生练习)
数据结构·算法·排序算法