Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
解题思路还是快慢指针,参考上图易知,X为链表起点,Y为链表环的入口,Z为fast与slow第一次相遇的地方,可知fast与slow第一次相遇的时候,slow走过的路程为a+b,fast走过的路程为a+b+c+b,又有2*(a+b) = a+b+c+b,因此可知a == c,所以指针A与B分别从X,Z处同速前进,则相遇时位置便是链表环的入口Y。
参考博客(https://blog.csdn.net/xy010902100449/article/details/48995255)
class Solution: def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None or head.next == None: return None fast = head.next.next slow = head.next while fast != None and fast.next != None and fast != slow: fast = fast.next.next slow = slow.next if fast == None or fast.next == None: return None slow = head while slow != fast: fast = fast.next slow = slow.next return slow