环形链表判断

题目:

141-环形链表

https://leetcode-cn.com/problems/linked-list-cycle/

解答:

思路:将访问过的放到一个容器中,然后判断当前访问的节点是否已经存在容器内

代码:

//141-1 放到容器中,判断当前的节点是否在已访问的容器内
bool hasCycle(ListNode *head) 
{
    vector<ListNode*> hasFound;
    while (head != nullptr)
    {
        if (hasFound.size() > 0 && find(hasFound.begin(), hasFound.end(), head) != hasFound.end())
            return true;

        hasFound.push_back(head);
        head = head->next;
    }

    return false;
}

提交后:5%,时间复杂度O(n),空间复杂度O(n),因为使用了额外的容器

解答二:双指针法--快慢指针

思路:

两个指针同时指向head,一个每次移动一个节点,一个每次移动两个节点,如果两个节点在某一时刻相遇,则有环;如果某个指针指向了nullptr则无环

原理:两个人绕跑道跑步,快的最终会套圈跑的慢的,也即是两者一段时间后必须相遇。

代码:

//快慢指针
bool hasCycle2(ListNode *head)
{
    if (head == nullptr)
        return true;
    ListNode* p1 = head;
    ListNode* p2 = head->next;    //注意:在这里不能将p2 赋值为head,不然 p1直接等于p2 了
    while (p1 != p2)//截止条件:p1 p2指向相同的节点
    {
        p1 = p1->next;
        if (p1 == nullptr)
            return false;
        if (p2->next == nullptr)
            return false;
        p2 = p2->next->next;
        if (p2 == nullptr)
            return false;
    }

    return true;
}
原文地址:https://www.cnblogs.com/zyk1113/p/14048802.html