求链表环的起始位置

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

相关推荐
2401_841495644 小时前
【数据结构】B+树
数据结构·数据库·c++·b+树·概念·结构·操作原理
皓月斯语6 小时前
【C++基础】三目运算符
开发语言·数据结构·c++
剑锋所指,所向披靡!7 小时前
数据结构之拓扑排序
数据结构
夜不会漫长10 小时前
数据结构:链表
数据结构·链表
剑锋所指,所向披靡!11 小时前
数据结构之关键路径
数据结构·算法
笨笨饿11 小时前
101_详解USB协议
java·jvm·数据结构
J-Tony1111 小时前
【Redis】数据结构&&持久化
数据结构·数据库·redis
来一碗刘肉面11 小时前
队列的链式实现
数据结构·c++·算法·链表
奶人五毛拉人一块13 小时前
二分算法以及习题讲解
数据结构·算法·二分
兰令水13 小时前
hot100【acm版】【2026.7.19打卡-java版本】
java·数据结构·算法·leetcode·面试