描述
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?
Linked List Cycle的升级版。要求不仅判断是否有环,而且要找出环开始的位置。
分析
对于存在环的情况,设从链表头部到环第一个元素的距离为x
,从环第一个元素到两指针相遇点距离为y
,环长度为r
。这里可以证明的一点是,当两指针相遇时,慢指针肯定没有跑完一圈。这样来证明:当慢指针到达环第一个元素时,快指针肯定在环中某个地方,设距离环第一个元素z
,肯定有z < r
。而快指针只需要z
步就可以追上慢指针,所以慢指针没有机会跑完一圈。
设相遇时已经走了t
步,则t = x + y
, 2t = x + y + nr
, 其中n
为正整数。则可以推导出t = nr
,x = nr - y = (n - 1)r + (r - y)
。这样一来,如果我们在两指针相遇后,再用一个指针从链表头开始走,直到它和慢指针相遇,相遇点就是环开始的地方。
代码
Python
1 | # Definition for singly-linked list. |