题目:链表中环的入口结点 描述 给一个长度为n链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
数据范围: n≤10000 节点值范围:[1,10000] 要求:空间复杂度 O(1),时间复杂度 O(n)
这个题目我之前有思路,但是只在环的长度大于前面链的情况下成立,看评论知道了方法,记录一下
```# -*- 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
fast = pHead
slow = pHead
isMeeting = False
while ((fast != None) & (fast.next != None)):
if isMeeting:
fast = fast.next
else:
fast = fast.next.next
if fast == None:
return
slow = slow.next
if slow == fast:
if slow == pHead:
return slow
if isMeeting:
return slow
slow = pHead
isMeeting = True
return