题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here slow = pHead fast = pHead while fast and fast.next: slow = slow.next fast = fast.next.next # 找到快慢指针相遇的点 if slow == fast: index1 = fast index2 = pHead # 利用数学推导 当 x = z 时即链表中环的入口节点 while index1!=index2: index1 = index1.next index2 = index2.next return index1 return None
数学推导,当x = z 时即为环入口