设置快慢指针,确定是否有环。如果有环,确定环中节点的数量。然后再根据快慢指针去找,找到环的入口点。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return None
slow = head
fast = head
pTemp = None
while slow and fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
else:
return None
if slow == fast:
pTemp = slow
break
if pTemp is None:
return None
pTemp1 = pTemp.next
n = 1
while pTemp1 != pTemp:
pTemp1 = pTemp1.next
n = n + 1
slow = head
fast = head
while n > 0:
fast = fast.next
n = n - 1
while slow != fast:
slow = slow.next
fast = fast.next
return slow