给定一个链表,如果链表中存在环,则返回到链表中环的起始节点,如果没有环,返回null。
力扣142题,领扣103题的
转载水中的鱼的推导过程
1.证明过程
首先,比较直观的是,先使用Linked List Cycle I的办法,判断是否有cycle。如果有,则从头遍历节点,对于每一个节点,查询是否在环里面,是个O(n^2)的法子。但是仔细想一想,发现这是个数学题。
如下图,假设linked list有环,环长Y,环以外的长度是X。
现在有两个指针,第一个指针,每走一次走一步,第二个指针每走一次走两步,如果他们走了t次之后相遇在K点
那么
指针一 走的路是 t = X + nY + K ①
指针二 走的路是 2t = X + mY+ K ②
m,n为未知数,把等式一代入到等式二中, 有
2X + 2nY + 2K = X + mY + K
=> X+K = (m-2n)Y ③
这就清晰了,X和K的关系是基于Y互补的。等于说,两个指针相遇以后,再往下走X步就回到Cycle的起点了。这就可以有O(n)的实现了。
2.代码
是慢回头走还是快回头走是一样的效果
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins. if there is no cycle, return null
*/
public ListNode detectCycle(ListNode head) {
//空参处理
if (head == null) return null;
boolean hasCycle = false;
//判断是否有环
ListNode fast = head, slow = head;
while ( fast!=null && fast.next != null && slow != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
hasCycle = true;
break;
}
}
//没环直接返回
if (!hasCycle) return null;
// slow = head;
// while (slow != fast) {
// slow = slow.next;
// fast = fast.next;
// }
//有环寻找起点
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
转载
http://fisherlei.blogspot.com/2013/11/leetcode-linked-list-cycle-ii-solution.html [LeetCode] Linked List Cycle II, Solution