142. 环形链表 II
#
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 None。
示例:
输入1:
输出1:
ListNode(2)
输入2:
输出2:
None
解答:
def detectCycle(self, head):
if head is None : return None
if head.next is None : return None
slow = fast = head
steps = 0
flag = False
while(fast and fast.next):
fast = fast.next.next
slow = slow.next
steps += 1
if (fast == slow):
flag = True
break
if not flag:
return None
else:
while(head!=slow):
slow = slow.next
head = head.next
return head