描述
分析
(1)使用快慢指针。慢指针每次移动移动到下一单元,快指针每次移动到下下个单元。这样若快慢指针最终相遇(指向同一块内存),便证明存在环。时间复杂度
O
(
n
)
O(n)
O(n),空间复杂度
O
(
1
)
.
O(1).
O(1).
(2)哈希法。时间复杂度和上面相同均为 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n).
代码
快慢指针
/**
* 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 || !head->next) return false;
ListNode *fast = head, *slow = head;
while(slow && fast){
slow = slow->next;
if(!fast->next) break;
fast = fast->next->next;
if(fast == slow) return true;
}
return false;
}
};