给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
设定块 慢指针,快指针没次走两步,慢指针每次走一步,如果有环,它们一定会相遇;否则快指针会先到最后。相遇后选一个指针在头结点,然后与慢指针同时移动,相遇位置就为环入口:
# -*- 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 not pHead or not pHead.next:
return None
slow, fast = pHead.next, pHead.next.next # 走一步和两步
while slow != fast:
if fast == None or fast.next == None:
return None
slow = slow.next
fast = fast.next.next
res = pHead
while res != slow:
res = res.next
slow = slow.next
return res