求链表环的起始位置

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

相关推荐
迷途之人不知返几秒前
数据结构初识,与算法复杂度
数据结构
DARLING Zero two♡1 小时前
【优选算法】D&C-Mergesort-Harmonies:分治-归并的算法之谐
java·数据结构·c++·算法·leetcode
louisdlee.2 小时前
树状数组维护DP——前缀最大值
数据结构·c++·算法·dp
minji...3 小时前
算法题 逆波兰表达式/计算器
数据结构·c++·算法·1024程序员节
循着风7 小时前
二叉树的多种遍历方式
数据结构·算法
.格子衫.12 小时前
022数据结构之树状数组——算法备赛
数据结构·算法·1024程序员节
Yupureki12 小时前
从零开始的C++学习生活 16:C++11新特性全解析
c语言·数据结构·c++·学习·visual studio
熬了夜的程序员13 小时前
【LeetCode】89. 格雷编码
算法·leetcode·链表·职场和发展·矩阵
對玛祷至昏14 小时前
数据结构理论知识
数据结构·算法·排序算法
黄思搏14 小时前
红黑树 - Red-Black Tree 原理与 C# 实现
数据结构·1024程序员节