版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Ming991301630/article/details/83060097
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
//判断链表是否有环
//方法:
//1、空间复杂度n:使用set集合保存每一个节点,判断是否有重复
//2、空间复杂度1:使用两个指针,快指针走两步,慢指针走一步;
// 若快指针为null则无环。
// 若快指针与慢指针相遇,快指针回到开头与慢指针一起每次只走一步,直至相遇为入环节点。
class Solution {
public:
ListNode * detectCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr)return nullptr;
ListNode *fastp = head, *slowp = head;
while (true)
{
if (fastp->next == nullptr || fastp->next->next == nullptr)return nullptr;//快指针为null则无环 + 防止访问到空指针
fastp = fastp->next->next;
slowp = slowp->next;
if (slowp == fastp)break;//快指针与慢指针相遇,则有环
}
fastp = head;
while (fastp != slowp)
{
fastp = fastp->next;
slowp = slowp->next;
}
return slowp;
}
};