

求解代码
java
public ListNode EntryNodeOfLoop(ListNode pHead) {
// 快慢指针都从链表头出发
ListNode fast = pHead;
ListNode slow = pHead;
while (fast != null && fast.next != null) {
fast = fast.next.next; // 快指针走2步
slow = slow.next; // 慢指针走1步
// 快慢指针相遇 → 证明链表有环,进入找入口逻辑
if (slow == fast) {
// 找环的入口
while (pHead != slow) {
pHead = pHead.next; // 头指针走1步
slow = slow.next; // 相遇点指针走1步
}
return slow; // 相遇时就是环的入口
}
}
// 无环,返回null
return null;
}