142. Linked List Cycle II
1. 问题描述:
输入是一个链表,要求判断是否有圈,如果有圈,返回圈的起点;否则返回null。
2. 解决思路:
之前141题是判断链表是否有圈,这一题是要求找到圈的起点。这里先证明一个结论。
假设现在有这样一个链表如图,并且有两个指针,1和2,1是慢指针(每次走1步),2是快指针(每次走2步);
当 1 指针到圈起点时,2指针的位置如下,其实此时2已经在圈中转了一圈;
这时如果继续走下去,1 和 2 一定会相遇,这里我们设柄长为 a,圈长为 n,1到圈起点,2在圈中位置为 x (0<=x<n) ,相遇点是如下图星符号所标,圈起点到相遇点距离为 b。1 和 2 经过 n−x 步相遇(追及问题)。
那当 1 和 2 相遇时,指针 2 走过的距离: d2=a+b+k∗n=2(a+b) (圈如果足够小,当指针1到圈起点前,指针2可能已经走了很多圈了)。所以是 k∗b ;指针 1 走过的距离: d1=a+b 。
根据 d2=a+b+k∗n=2(a+b) ,可以得到 a+b=k∗n 。这是什么意思呢?就是指针 1 所走的长度就是圈长的整数倍。所以当他们指针相遇时,这时把指针 2 拉回起点,一次走一步。指针 1继续从相遇点走,a 步之后两指针会在圈起点相遇。这样就知道了圈起点,返回圈起点。
3. java代码:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {//两个指针相遇
fast = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}