求链表环的起始位置

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

相关推荐
:-)11 小时前
算法-希尔排序
数据结构·算法·排序算法
罗超驿1 天前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)1 天前
算法-堆排序
数据结构·算法·排序算法
j7~1 天前
【数据结构初阶】顺序表增删查改代码实现--详解
数据结构·顺序表·动态顺序表·静态顺序表
枕星而眠1 天前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
:-)1 天前
基础算法-选择排序
数据结构·算法·排序算法
粘稠的浆糊1 天前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
海清河晏1111 天前
数据结构 | 二叉平衡搜索树
开发语言·数据结构·visual studio
兰令水1 天前
hot100【acm版】【2026.7.11/12打卡-java版本】
java·开发语言·数据结构·算法·职场和发展
叩码以求索1 天前
使用next数组加速匹配过程
java·数据结构·算法