给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
if (pHead == null || pHead.next == null) return null;
ListNode pFast = pHead;
ListNode pSlow = pHead;
//pFast两步一走,pSlow一步一走,必相遇
while (pFast.next.next != null && pSlow.next != null) {
pFast = pFast.next.next;
pSlow = pSlow.next;
if (pFast == pSlow) {
break;
}
}
//they met其中一个回到起点,两两一步一走必在入口相遇
pSlow = pHead;
while (pFast != pSlow) {
pFast = pFast.next;
pSlow = pSlow.next;
}
return pFast;
}