求链表环的起始位置

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_8414956414 分钟前
【LeetCode刷题】二叉树的中序遍历
数据结构·python·算法·leetcode··递归·遍历
踩坑记录9 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
历程里程碑12 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
派大鑫wink13 小时前
【Day61】Redis 深入:吃透数据结构、持久化(RDB/AOF)与缓存策略
数据结构·redis·缓存
独处东汉14 小时前
freertos开发空气检测仪之输入子系统结构体设计
数据结构·人工智能·stm32·单片机·嵌入式硬件·算法
放荡不羁的野指针14 小时前
leetcode150题-滑动窗口
数据结构·算法·leetcode
BHXDML14 小时前
数据结构:(一)从内存底层逻辑理解线性表
数据结构
小龙报14 小时前
【C语言进阶数据结构与算法】单链表综合练习:1.删除链表中等于给定值 val 的所有节点 2.反转链表 3.链表中间节点
c语言·开发语言·数据结构·c++·算法·链表·visual studio
Anastasiozzzz15 小时前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
xuedingbue16 小时前
数据结构与顺序表:高效数据管理秘籍
数据结构·算法·链表