https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
思路:快慢指针,注意边界判断
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) return false; // 链表为空 不存在环
ListNode *slow = head, *fast = head->next; // 快慢指针
// 若存在环 两指针必定相遇
while (slow != fast) {
slow = slow->next;
// 若fast走到尽头 则必定不存在环
if (fast && fast->next) fast = fast->next->next;
else return false;
}
return true; // 两指针相遇且不为空 存在环
}
};



