环形链表 II
环形链表 II
/**
* 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;
//快指针跳2步,慢指针跳1步,如果有环的话,两指针一定会相遇
if(slow==fast){
//推理得公式x=nz+(n-1)y;x:起点到入环结点,y:入换节点到相遇结点,z:相遇结点到入环结点
ListNode index1 = fast;
ListNode index2 = head;
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}