题目
思路
快慢指针。先用快慢指针找到是否有环。当有环时,慢指针设置为head,快指针步长设置为1,继续遍历,相遇的点就是入口。
代码
# 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 """
p1 = head; p2 = head
while p1 and p2 and p2.next:
p1 = p1.next
p2 = p2.next.next
if p1 == p2:
p1 = head
while p1 and p2:
if p1 == p2:
return p1
p1 = p1.next
p2 = p2.next
return None