求链表环的起始位置

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

相关推荐
热心市民小刘05052 小时前
11.18二叉树中序遍历(递归)
数据结构·算法
未若君雅裁2 小时前
LeetCode 18 - 四数之和 详解笔记
java·数据结构·笔记·算法·leetcode
小欣加油3 小时前
leetcode 429 N叉树的层序遍历
数据结构·c++·算法·leetcode·职场和发展
Kuo-Teng3 小时前
LeetCode 142: Linked List Cycle II
java·算法·leetcode·链表·职场和发展
星轨初途4 小时前
《数据结构二叉树之堆 —— 优先队列与排序的高效实现(2)(下)》
c语言·开发语言·数据结构·经验分享·笔记·性能优化
高山有多高5 小时前
堆应用一键通关: 堆排序 +TOPk问题的实战解析
c语言·数据结构·c++·算法
前进之路96 小时前
Leetcode每日一练--47
数据结构·算法·leetcode
晨非辰7 小时前
【数据结构初阶系列】归并排序全透视:从算法原理全分析到源码实战应用
运维·c语言·数据结构·c++·人工智能·python·深度学习
泡沫冰@12 小时前
数据结构(20)
数据结构
Miraitowa_cheems14 小时前
LeetCode算法日记 - Day 106: 两个字符串的最小ASCII删除和
java·数据结构·算法·leetcode·深度优先