class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast=head,*slow=head;
while(fast && slow){
fast=fast->next;
if(!fast) return false;
fast=fast->next;
slow=slow->next;
if(fast==slow) return true;
}
return false;
}
};
还是一个快慢指针的题目。要注意一点是,快指针不仅要判断p!=NULL 还要判断!p->next.