这是一个用快慢指针判断链表是否存在环的程序,leetcode 141请问为什么我这样写没法通过全部用例,未通过的用例是[1, 2](无环)
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast = head, *slow = head;
while(fast != nullptr && fast->next != nullptr && fast != slow){
slow = slow->next;
fast = fast->next->next;
}
if(fast == nullptr || fast->next == nullptr){
return false;
}else{
return true;
}
}
};