求链表环的起始位置

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

相关推荐
LuminousCPP16 小时前
数据结构‑二叉树(二):二叉堆从零实现|Heap结构设计 + 建堆优化 + 堆排序深度解析
c语言·数据结构·笔记·二叉树
18 小时前
数据结构第一课:复杂度解析
数据结构
欧叶冲冲冲19 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
_Narcissus_20 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.20 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
疯狂打码的少年1 天前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法
青 春 记 忆1 天前
LeetCode 206. 反转链表|Python 解法详解
python·leetcode·链表
啊嘞嘞?1 天前
力扣(回文链表)
算法·leetcode·链表
Awh-1 天前
数据结构 第六章:哈希存储
数据结构·算法·哈希算法
TAN-90°-1 天前
Deep Learning for Computer Vision——Recurrent Neural Networks
数据结构·人工智能·rnn·深度学习·神经网络·机器学习·计算机视觉