力扣-链表-142 环形链表Ⅱ
思路
利用快慢指针判断环是否存在,然后利用数学公式找到存在环的情况下找入口
代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL || head->next==NULL || head->next->next == NULL){
return NULL;
}
ListNode* fast = new ListNode();
ListNode* slow = new ListNode();
fast = head->next->next;
slow = head->next;
while(fast != slow){
if(fast->next == NULL || fast->next->next == NULL || slow->next == NULL){
return NULL;
}
fast = fast->next->next;
slow = slow->next;
}
ListNode* index1= head;
ListNode* index2 = fast;
while(index1 != index2){
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
};