快慢指针的应用。慢指针每次一步,快指针每次两步。要是有环的话终究是要相遇的。
bool hasCycle(ListNode *head) {
ListNode*slow=head,*fast=head;
if(!head) return false;
while(fast){
slow=slow->next;
fast=fast->next;
if(fast)
fast=fast->next;
else return false;
if(fast==slow)
return true;
}
return false;
}
bool hasCycle(ListNode *head) {
ListNode*slow=head,*fast=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
return true;
}
return false;
}
bool hasCycle(ListNode *head) {
ListNode*slow=head,*fast=head;
while(fast&&fast->next&&fast->next->next){
slow=slow->next;
fast=fast->next->next->next;
if(fast==slow)
return true;
}
return false;
}
跑的快的终极是要追上跑的慢的,理想情况下,快的是慢的2倍时,当慢的跑完一次全程,快的已经跑完2次的全程。