diff --git a/notes/23. 链表中环的入口结点.md b/notes/23. 链表中环的入口结点.md index 64c6f21b..4e38045f 100644 --- a/notes/23. 链表中环的入口结点.md +++ b/notes/23. 链表中环的入口结点.md @@ -1,6 +1,6 @@ # 23. 链表中环的入口结点 -[NowCoder](https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tqId=11208&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/linked-list-cycle-ii/) ## 题目描述 @@ -25,19 +25,22 @@

```java -public ListNode EntryNodeOfLoop(ListNode pHead) { - if (pHead == null || pHead.next == null) +public ListNode detectCycle(ListNode head) { + if (head == null || head.next == null) return null; - ListNode slow = pHead, fast = pHead; - do { + ListNode slow = head, fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; fast = fast.next.next; - slow = slow.next; - } while (slow != fast); - fast = pHead; - while (slow != fast) { - slow = slow.next; - fast = fast.next; + if (slow == fast) { + fast = head; + while (slow != fast) { + slow = slow.next; + fast = fast.next; + } + return slow; + } } - return slow; + return null; } ```