1.设置快慢指针,慢指针每次移动一步,快指针每次移动两步.
2.如果链表有环,必定慢指针和快指针在某一个点相遇,记为meet.
根据数学知识:fast和slow相遇的地方到入口等于头节点到入口的距离
3.这时meet和和head指针同时再移动,如果移动到两个指针相等,则为环形入口地址.
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL){
return NULL;
}
ListNode *slow=head;
ListNode *fast=head;
ListNode *meet;
while(slow&&fast){
slow=slow->next;
fast=fast->next;
if(fast==NULL){
return NULL;
}
fast=fast->next;
if(fast==slow){
meet=fast;
break;
}
}
while(head&&meet){
if(head==meet){
return head;
}
head=head->next;
meet=meet->next;
}
return NULL;
}
};
京公网安备 11010502036488号