Leetcode141题:给定一个链表,判断链表中是否有环。
主要有两种方法,利用哈希表存储和快慢指针方法,快慢指针方法占用内存较少且泛用性较高,故在此记录。
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr){
return false;
}
ListNode* slow = head;
ListNode* fast = head->next;
while(slow != fast){
if(fast == nullptr || fast->next == nullptr){
// 如果没有环,快指针会先到达结尾
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
作者:linuzb
链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/141-huan-xing-lian-biao-kuai-man-zhi-zhen-c-by-lin/
来源:力扣(LeetCode)