142. 环形链表 II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
相遇之后,fast 和slow都用一倍速跑,相遇的地方便是起点
# 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:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
fast = head#将fast放到起始位置
break
if fast is None or fast.next is None:
return None
while fast != slow:
slow = slow.next
fast = fast.next
return slow