1、解题思路
建立等式,求解x。已知,快指针的路程为慢指针的两倍,快指针的路程可描述为:x+y+n(y+z),慢指针的路程可描述为:x+y。求解x+y+n(y+z)=2*(x+y)
整理公式:x = (n - 1) (y + z) + z ,当n=1,x=z,从相遇处到入口和头结点到入口的距离相同,当n≠1,说明从相遇点出发,转圈后能与从头节点出发的点在入口处相遇。
2、
首先改写了一下之前的环查找,把循环条件和判断条件调换了位置,将初始位置都定在了head处,符合我们的原理。从相遇点和头节点出发,以同样的速度前进,相遇位置即为环节点。
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head and head.next is None:#两者其一为None 1&0=0
return None
piont=self.hashCycle(head)
if piont is None: #没有环
return None
head1=head
while piont!=head1:
piont=piont.next
head1=head1.next
return piont
def hashCycle(self,head:ListNode): #查找相遇点
fast=head
slow=head
while fast and fast.next is not None:
fast=fast.next.next
slow=slow.next
if fast==slow:
return fast
return None
之前查环形链表节点的写法,要求初始化必须不同:
while fast!=slow:
if not fast or not fast.next:
return False
slow=slow.next
fast=fast.next.next