环形链表 II
https://leetcode.cn/problems/linked-list-cycle-ii/ (opens new window) 需要注意的点 1. 环头节点(环头),链表的头节点(链头),fast 跟slow 相遇的节点(相遇点) 走n圈,环头到链头为a,slow 到相遇点为b, fast 在环里面走c, 环的长度是b+c fast走过的距离是 fast = a + n(b+c)+b = a + (n+1)b+nc slow走过的距离是 slow = a+b 等式 a + (n+1)b+nc = 2(a+b) == a = c + (n-1)(b+c)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
'''
环头节点(环头),链表的头节点(链头),fast 跟slow 相遇的节点(相遇点)
走n圈,环头到链头为a,slow 到相遇点为b, fast 在环里面走c,
环的长度是b+c
fast走过的距离是
fast = a + n(b+c)+b = a + (n+1)b+nc
slow走过的距离是
slow = a+b
等式
a + (n+1)b+nc = 2(a+b)
== a = c + (n-1)(b+c)
'''
slow = head
fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
a = fast
b = head
while a != b:
a = a.next
b = b.next
return a
return None