传送门
nowcoder
leetcode
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出 null。
C++ 代码 - nowcoder
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { if (pHead == nullptr) return nullptr;
unordered_map<ListNode*, int> map; ListNode* p = pHead; while (p != nullptr) { map[p] ++; if (map[p] == 2) return p; p = p->next; } return nullptr; } };
class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { if (pHead == nullptr || pHead->next == nullptr) return nullptr;
ListNode *fast = pHead, *slow = pHead; while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; slow = slow->next; if (fast == slow) break; }
if (fast == nullptr || fast->next == nullptr) return nullptr; slow = pHead; while (fast != slow) { fast = fast->next; slow = slow->next; } return fast; } };
|
C++ 代码 - leetcode
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 30
|
class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == nullptr || head->next == nullptr) return nullptr;
ListNode *fast, *slow; fast = slow = head; while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; slow = slow->next; if (fast == slow) break; }
if (fast == nullptr || fast->next == nullptr) return nullptr;
slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; } };
|