求链表环的起始位置

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

相关推荐
buyue__8 分钟前
C++实现数据结构——链表
数据结构·c++·链表
Ayanami_Reii32 分钟前
进阶数据结构应用-SPOJ 3267 D-query
数据结构·算法·线段树·主席树·持久化线段树
Genevieve_xiao2 小时前
【数据结构与算法】【xjtuse】面向考纲学习(下)
java·数据结构·学习·算法
仰泳的熊猫2 小时前
1031 Hello World for U
数据结构·c++·算法·pat考试
liu****2 小时前
12.C语言内存相关函数
c语言·开发语言·数据结构·c++·算法
FMRbpm2 小时前
栈练习--------从链表中移除节点(LeetCode 2487)
数据结构·c++·leetcode·链表·新手入门
C雨后彩虹3 小时前
矩阵扩散问题
java·数据结构·算法·华为·面试
sin_hielo3 小时前
leetcode 3432
数据结构·算法·leetcode
代码游侠4 小时前
数据结构——树
数据结构·算法