Leetcode 142. Linked List Cycle II
步骤为:
判断是否有环 —>没有 return None
—>有 一个一个走直到在环的入口相遇
代码如下:
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
slow = head
fast = head.next
while fast != None:
if(slow == fast):
slow = head
fast = fast.next
while slow != fast:
slow = slow.next
fast = fast.next
#print(slow.val, fast.val)
return slow
else:
slow = slow.next
if(fast.next == None):
return None
fast = fast.next.next
return None
beat 99%
数学味很浓的一道题,特别是后面解决在入口相遇的推理我很喜欢。
比较好的解析在评论中:讨论了大环和小环可能的求解差异
https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode/