题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null(None)。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
# 需要定义两个指针,其中一个跳两步,一个跳一步
# 循环跳
# 要么是快的指针为空(没有环),要么是快慢相等(有环)
if pHead == None:
return None
fastpointer = pHead
slowpointer = pHead
#判断链表中是否有环
while fastpointer and fastpointer.next:
fastpointer = fastpointer.next.next
slowpointer = slowpointer.next
if slowpointer == fastpointer:
break
if fastpointer == None or fastpointer.next == None:
return None
# 如果slow走了l的长度,那么fast就走了2l的长度
# 假设从开始到入口点的长度是s,slow 在环里面走的长度是d
# 那么 l = s + d
# 假设 环内slow没走的长度是m ,那么fast走的长度是slow的两倍,并且m+d为环的长度
# fast走的长度就是 n*(m + d) + d + s =2l n为环内的圈数
# 带入 n*(m+d) + d + s = (s + d)*2
# 化简 n*(m+d)+d+s = (s+d)*2
# n*(m+d)= s + d
# s = n*(m+d)-d
# s = n*m + (n-1)*d
# s = m + (n-1)*(m+d)
fastpointer = pHead
while fastpointer != slowpointer:
fastpointer = fastpointer.next
slowpointer = slowpointer.next
return fastpointer
解法思路见
https://zhuanlan.zhihu.com/p/103626709