求链表环的起始位置

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

相关推荐
不穿格子的程序员3 小时前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
dragoooon343 小时前
[hot100 NO.19~24]
数据结构·算法
电子硬件笔记4 小时前
Python语言编程导论第七章 数据结构
开发语言·数据结构·python
Tony_yitao4 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹5 小时前
任务总执行时长
java·数据结构·算法·华为·面试
柒.梧.5 小时前
数据结构:二叉排序树构建与遍历的解析与代码实现
java·开发语言·数据结构
zhuzewennamoamtf6 小时前
Linux内核platform抽象、数据结构、内核匹配机制
linux·运维·数据结构
不穿格子的程序员7 小时前
从零开始写算法——链表篇5:K个一组翻转链表 + 排序链表
算法·链表·分治
自然常数e8 小时前
深入理解指针(6)
c语言·数据结构·算法·visual studio
一杯美式 no sugar8 小时前
数据结构——栈
c语言·数据结构·