腾讯五十题No.31 环形链表II
判断环的入口,需要先判断有没有环,在寻找环的入口,找入口时需要重新定义两个”指针“,一个指向头节点,一个指向当前fast,让他们前进速度相同,他们想入的点即为入口。
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head,slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
//判断是否有环
if(fast==slow){
ListNode index1 = fast;
ListNode index2 = head;
//查找环入口
while(index1!=index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}

本文来自博客园,作者:蹇爱黄,转载请注明原文链接:https://www.cnblogs.com/jianjiana/p/15872011.html

浙公网安备 33010602011771号