【刷题日记】链表-环形链表II-L142-Medium
给定一个链表的头节点 head,返回链表开始入环的第一个节点。如果链表无环,则返回 null。
代码
哈希表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *p = head; std::unordered_set<ListNode*> us;
while (p != nullptr) { if (us.count(p)) return p; us.insert(p); p = p->next; } return p; } };
|
快慢指针
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
| class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode* fast = head; ListNode* slow = head; while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; slow = slow->next; if (slow == fast) { ListNode* index1 = head; ListNode* index2 = fast; while (index1 != index2) { index1 = index1->next; index2 = index2->next; } return index1; } } return nullptr; } };
|