题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
public class Solution { // 思路: // 1、判断链表是否有环 // 使用快慢指针,快指针走两步,慢指针走一步,如果快慢指针相遇就有环(循环条件快指针和快指针的next不为空) // 2、找相遇节点 // 返回找环时相遇的慢指针,定义另一个快指针从头出发,快慢指针相遇处就是入口 public ListNode EntryNodeOfLoop(ListNode pHead) { ListNode slow = judgeCircle(pHead); if (slow == null) return null; ListNode fast = pHead; while (fast != slow) { fast = fast.next; slow = slow.next; } return fast; } public ListNode judgeCircle(ListNode head) { ListNode slow = head,quick = head; while (quick != null && quick.next != null) { slow = slow.next; quick = quick.next.next; if (slow == quick) return slow; } return null; } }