diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" index 522f51c2ac45b1721729b0c279162ee1ea83ebb1..15531f67eeeffdfbdb5387a973e3300520c55017 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\345\217\214\346\214\207\351\222\210\346\212\200\345\267\247.md" @@ -18,7 +18,7 @@ [141.环形链表](https://leetcode-cn.com/problems/linked-list-cycle) -[141.环形链表II](https://leetcode-cn.com/problems/linked-list-cycle-ii) +[142.环形链表II](https://leetcode-cn.com/problems/linked-list-cycle-ii) [167.两数之和 II - 输入有序数组](https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted) @@ -280,3 +280,40 @@ public class Solution { } ``` +[zhengpj95](https://github.com/zhengpj95) 提供 【2、已知链表中含有环,返回这个环的起始位置】 C++ 代码 + +> 其实快慢指针问题,也就是著名的 *[Floyd's cycle detection algorithm](https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_Tortoise_and_Hare)* 问题。 + +```c++ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + // 如果链表为空或者第一个结点的指针为空,则无环 + if (!head || !head->next) { + return NULL; + } + + // 快慢指针找相遇点 + ListNode *fast = head, *slow = head; + while (fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) { + break; + } + } + // 如果没有相遇点,表示没有环,直接返回即可 + // 此时,快慢指针要么指向同一个结点,要么快指针指向空(偶数个结点)或者倒数第一个结点(奇数个结点) + if (fast != slow) { + return NULL; + } + //让慢指针回到第一个结点,然后快慢指针重新同步前进,两指针相遇时就是环的起点位置 + slow = head; + while (fast != slow) { + fast = fast->next; + slow = slow->next; + } + return fast; + } +}; +```