求链表环的起始位置

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

相关推荐
code小毛孩1 小时前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
艾伦~耶格尔8 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
闪电麦坤9510 小时前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
快去睡觉~10 小时前
力扣400:第N位数字
数据结构·算法·leetcode
汤永红12 小时前
week1-[循环嵌套]画正方形
数据结构·c++·算法
pusue_the_sun12 小时前
数据结构——顺序表&&单链表oj详解
c语言·数据结构·算法·链表·顺序表
yi.Ist13 小时前
图论——Djikstra最短路
数据结构·学习·算法·图论·好难
数据爬坡ing13 小时前
过程设计工具深度解析-软件工程之详细设计(补充篇)
大数据·数据结构·算法·apache·软件工程·软件构建·设计语言
呼啦啦啦啦啦啦啦啦15 小时前
【Java】HashMap的详细介绍
java·数据结构·哈希表
qq_5139704415 小时前
力扣 hot100 Day74
数据结构·算法·leetcode