Loading...

链表中环的入口结点

在这里插入图片描述 在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
    }
最后更新于 2026-04-05 17:35:33
Code Road Record