給定一個單鏈表,判斷其中是否存在環。進階要求:不使用額外空間(O(1) 空間)。
slow 每次移動 1 步,快指針 fast 每次移動 2 步。fast 終將遇到 nullptr。fast 會在環內追上 slow,兩者相遇。/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) return false;
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};