链表中环的入口结点(important!)

题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

python solution:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def EntryNodeOfLoop(self, pHead):
        if not pHead or not pHead.next:
            return None
        fast,slow = pHead,pHead
        #判断是否有环
        l = 1
        while fast.next.next:
            fast = fast.next.next
            slow = slow.next
            if fast==slow: #判断环有多长
                # print(fast.val,slow.val)
                fast = fast.next
                while fast!=slow:
                    fast = fast.next
                    l += 1
                # print(l)
                #寻找入口结点
                fast,slow = pHead,pHead
                while l>0:
                    l -= 1
                    slow = slow.next
                while fast!=slow:
                    fast = fast.next
                    slow = slow.next
                return fast
        return None
原文地址:https://www.cnblogs.com/bernieloveslife/p/10431564.html