慢指针一次移动一下,快指针一次移动两下,如果链表中存在环,那么快慢指针一定会相遇。
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL){
return false;
}
ListNode* slowNode = head;
ListNode* fastNode = head->next;
while(fastNode!=slowNode){
if(fastNode==NULL||fastNode->next==NULL){
return false;
}
slowNode = slowNode->next;
fastNode = fastNode->next->next;
}
return true;
}
};