链表
解法一:
class solution{
public:
ListNode* detectCycle(ListNode *head){
unordered_map<ListNode *,int> cnt;//记录链表中每个节点出现的次数,切记不要用val值
if(head == nullptr || head->next == nullptr) //作为键;
return nullptr; //处理空链表或者只有一个节点的情况,一定没有环;
while(head){
if(++cnt[head] == 2)//当同一节点在遍历时出现两次,则说明有环;
return head;//且此时的head就是环的入口;
head = head->next;
}
return nullptr;//跳出循环说明head为空,走到了链表最后,没有环出现;
}
}
解法二:
class solution{
public:
ListNode * detectCycle(ListNode * head){
if(head == nullptr || head->next == nullptr)
return nullptr;
ListNode * slow = head;
ListNode * fast = head;
while(fast){
fast = fast->next->next;//快指针每次前进两步;
slow = slow->next;//慢指针每次前进一步;
if(fast == slow){
ListNode * index1 = fast;//记录快慢指针相遇位置;
ListNode * index2 = head;//再让另一指针从头开始走一次;
while(index1 != index2){ //两指针相遇时,就是环的入口;
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return nullptr;
}
}