public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode intersect = getIntersect(pHead);
if (intersect != null) {
// 找到相交结点之后只需要与头节点同时前进即可相遇
while (intersect != pHead) {
intersect = intersect.next;
pHead = pHead.next;
}
}
return intersect;
}
// 找出快慢指针相交的结点,若没有则返回null
private ListNode getIntersect(ListNode head) {
ListNode slow, fast;
slow = fast = head;
while (fast != null && fast.next != null) {
// 快指针一次前进两步,慢指针一次一步
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return fast;
}
}
return null;
}