給定單鏈表頭節點,判斷鏈表中是否存在環。進階:不使用額外空間(O(1) 空間複雜度)。
slow 每次走 1 步,fast 每次走 2 步。fast 先到達 nullptr。/**
* Definition for singly-linked list.
* struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head || !head->next) 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;
}
};
環長 L,快慢指針進環後相對速度 1 步/輪,至多 L 輪相遇。時間 O(n),空間 O(1)。
相遇後,將一指針重置為 head,兩指針同速前進,再次相遇點即為環入口。