求链表环的起始位置

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

相关推荐
凉茶钱3 小时前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
敲代码的苦134 小时前
头歌数据结构-排序的实现及其应用
数据结构
有同事要进步5 小时前
Leecode第68题:x的平方根
java·数据结构·算法
Pniubi5 小时前
HashMap扩容全流程
java·开发语言·数据结构
by209991 天前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表
Code_Solitude1 天前
c语言:关于qsoet函数知识点
c语言·数据结构·算法
Pniubi1 天前
快速排序(力扣基础)(递归)
java·数据结构·算法
lojox1 天前
C++ 手写 STL list(双向循环链表)原理剖析与实现
c++·链表·list
inrichtt2 天前
第八课时:SPI总线揭秘:四线全双工通信的奥
c语言·数据结构·stm32·单片机·嵌入式硬件
HPtiger2 天前
数据结构——选择排序
数据结构·算法·排序算法