LeetCode:142. 环形链表 II(哈希表和快慢指针(龟兔赛跑)法 C++带详细注释)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//哈希表法
// unordered_set<ListNode*>hash;//建立一个哈希表
// while(head)//head非空循环
// {
// if(hash.count(head)) return head;//第一个重复的即为环入口
// hash.insert(head);//将head放入hash表
// head=head->next;//head后移
// }
// return nullptr;//循环结束无环
ListNode*slow=head,*fast=head;//快慢指针法
do{
if(fast==nullptr||fast->next==nullptr) return nullptr;//fast走到头,无环
fast=fast->next->next;//fast金两步
slow=slow->next;//slow进一步
}while(fast!=slow);//不相等循环
ListNode*ptr=head;//ptr指向head,ptr到环入口距离等于slow到入口距离c+若干圈
while(ptr!=slow)//让ptr和slow在入口相遇
{
ptr=ptr->next;
slow=slow->next;
}
return ptr;//返回一个
}
};