此题设快慢两个指针,先判断是否有环:如果为环快慢指针终会相遇;
找入口节点:快慢指针相遇的节点到入口节点的距离,与从头节点开始新的慢指针到相遇点的距离相同。
可画图演示。因为快指针是慢指针的两倍速,且他们在q点相遇,则我们可以得到等式 2(A+B) = A+B+C+B.得出C=A
function EntryNodeOfLoop(pHead){
if(pHead == null || pHead.next == null||pHead.next.next==null){
return null;
}
let fast = pHead;
let slow = pHead;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
let slow2 = pHead;
while(slow2 != slow){
slow2 = slow2.next;
slow = slow.next;
}
return slow2;
}
}
}
来源:https://www.cnblogs.com/mlebk/p/12396046.html