Lc 环形链表Ⅱ
思路:
1.判断链表是否成环-- 定义快慢指针,一个每次走两步,一个每次走一步,相对就是多走一步,所以一定会相遇。若fast != null && fast.next != null 时对两指针进行移动,若一直到slow与fast相遇(此时一定在环中)从而证明有环,如果 fast == null || fast.next == null 直接跳出循环,则没环。
2.判断出有环之后
此时fast == slow 在A点相遇,根据fast速度为slow两倍,即路程也为两倍,则有
//(x + y) * 2 == x + n * (y + z) + y
//x == n * (y + z) + y == (n - 1) * (y + z) + z
也就是说走了x和走了(n - 1)圈+z的路程是一样的,即 从head出发走x与从break的相遇点A出发绕圈再次相遇时刚好相遇到环的起点B
代码:
/**
* 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 fast = head;
ListNode slow = head;
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
//快慢指针相遇(一定是从环里相遇,从而证明链表有环)
if (fast == slow){
ListNode index1 = head;
ListNode index2 = fast;
while (index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}