JZ55 链表中环的入口结点
本文最后更新于:2022年4月9日 中午
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode *fast = pHead; ListNode *slow = pHead; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; if (fast == slow) break; } if (!fast || !fast->next) return nullptr; fast = pHead; while (fast != slow) { fast = fast->next; slow = slow->next; } return fast; } };
|