求链表环的起始位置

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

相关推荐
H_z___2 小时前
Codeforces Round 1070 (Div. 2) A~D F
数据结构·算法
如竟没有火炬5 小时前
四数相加贰——哈希表
数据结构·python·算法·leetcode·散列表
仰泳的熊猫5 小时前
1148 Werewolf - Simple Version
数据结构·c++·算法·pat考试
不穿格子的程序员5 小时前
从零开始学算法——链表篇3:合并两个有序链表 + 两数相加
数据结构·算法·链表·dummy
子一!!5 小时前
数据结构==LRU Cache ==
数据结构
hweiyu006 小时前
数据结构:邻接矩阵
数据结构
Fine姐7 小时前
数据结构01——栈
数据结构
hweiyu007 小时前
数据结构:有向无环图
数据结构
liu****7 小时前
10.排序
c语言·开发语言·数据结构·c++·算法·排序算法
利刃大大7 小时前
【JavaSE】十一、Stack && Queue && Deque && PriorityQueue && Map && Set
java·数据结构·优先级队列··哈希表·队列·集合类