题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*function ListNode(x){ this.val = x; this.next = null; }*/ function EntryNodeOfLoop(pHead) { if (!pHead || !pHead.next) return null; // 先判断是否有环 let slow = pHead.next, fast = pHead.next.next; while (fast && fast.next && fast !== slow) { slow = slow.next; fast = fast.next.next; } if (!fast || !fast.next) return null; slow = pHead; while (fast !== slow) { slow = slow.next; fast = fast.next; } return slow; } module.exports = { EntryNodeOfLoop: EntryNodeOfLoop, };
判断链表是否有环,并且找到环的入口结点经典题。
慢指针走一步,快指针走两步,相遇则有环。
相遇后,慢指针再从头开始走,再次相遇的时候就是环入口点。