求链表环的起始位置

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

相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构