求链表环的起始位置

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

相关推荐
一起努力啊~13 分钟前
算法刷题--螺旋矩阵II+区间和+开发商购买土地
数据结构·算法·leetcode
ID_180079054733 小时前
小红书笔记详情API接口基础解析:数据结构与调用方式
数据结构·数据库·笔记
iuu_star9 小时前
C语言数据结构-顺序查找、折半查找
c语言·数据结构·算法
漫随流水10 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
千金裘换酒12 小时前
LeetCode反转链表
算法·leetcode·链表
一起努力啊~15 小时前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
小北方城市网15 小时前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)
大数据·网络·数据结构·python·架构·数据库架构
好易学·数据结构15 小时前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
独自破碎E15 小时前
【归并】单链表的排序
数据结构·链表
L_090716 小时前
【C++】高阶数据结构 -- 平衡二叉树(AVLTree)
数据结构·c++