剑指 Offer II 022. 链表中环的入口节点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
#首先判断是不是有环
if not head:
return
elif head.next is None:
return None
elif head.next.next is None:
return None
last, end = head, head
flag = False
while last and end:
last = last.next
if end.next:
end = end.next.next
else:
return None
if last == end:
flag = True
break
#确定环的输入口
if flag:
end = head
while 1:
if last == end:
return last
last = last.next
end = end.next
else:
return None