class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode*slow=head;
ListNode*fast=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)return true;
}
return false;
}
};
快指针每次两步,慢指针每次移动一步,若链表有环,则快慢指针总会相遇;