1、设置快慢指针,每次,快指针走两步,慢指针走一步,若有环,最后一定相遇;
2、相遇后,两个指针分别从链表头和相遇点继续出发,每次走一步,最后一定相遇于环入口。
表头到环入口长度为 a,环入口到相遇点长度为 b,相遇点到环入口长度为 c
快指针走的路程为:a+(b+c)k+b
慢指针走的路程为:a+b
则有 (a+b)*2 = a+(b+c)k+b,化简得 a = (k-1)(b+c)+c
a 的长度为 (k-1)圈环的长度 加上 距离 c
则 两个指针分别从链表头和相遇点出发,最后一定相遇于环入口。
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return null;
}
ListNode low = pHead;
ListNode fast = pHead;
while (fast != null && fast.next != null) {
low = low.next;
fast = fast.next.next;
if (fast == null) {
return null;
}
if (low == fast) {
break;
}
}
fast = pHead;
while (fast != low) {
fast = fast.next;
low = low.next;
}
return fast;
}
}
import java.util.HashMap;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if(pHead == null || pHead.next==null || pHead.next.next==null)
return null;
ListNode pFast = pHead.next.next;
ListNode pLow = pHead.next;
while(pFast != pLow){
if(pFast==null || pLow==null)
return null;
if(pFast.next==null || pFast.next.next==null)
return null;
pFast = pFast.next.next;
if(pLow.next==null) return null;
pLow = pLow.next;
}
pLow = pHead;
while(pLow != pFast){
pLow = pLow.next;
pFast = pFast.next;
}
return pLow;
}
}
参考文章:
https://blog.csdn.net/zhuibushixi/article/details/114628509