【LeetCode】剑指 Offer II 022. 链表中环的入口节点
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> ptt;
ListNode * dummy = head;
while(dummy!=NULL){
if(ptt.count(dummy)){
return dummy;
}
ptt.insert(dummy);
dummy=dummy->next;
}
return NULL;
}
};
1.哈希表法
将访问过的节点存入set容器中,若遍历时再次遇到此节点,说明这里是环的入口
2.双指针法

通过证明可知,从起点开始,2倍速的快指针和慢指针相遇的时候,我们再额外使用一个指针ptr。起始,它指向链表头部;随后,它和 slow 每次向后移动一个位置。最终,它们会在入环点相遇。
样例代码:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr) {
slow = slow->next;
if (fast->next == nullptr) {
return nullptr;
}
fast = fast->next->next;
if (fast == slow) {
ListNode *ptr = head;
while (ptr != slow) {
ptr = ptr->next;
slow = slow->next;
}
return ptr;
}
}
return nullptr;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/c32eOV/solution/lian-biao-zhong-huan-de-ru-kou-jie-dian-vvofe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号