解析

Hash表,遍历链表节点,先判断表中是否已经存在。如果存在就是证明有环,不存在就将节点保存进Hash表,直到遍历到nullptr证明没有环。

代码

    bool hasCycle(ListNode *head) 
    {
        unordered_set<ListNode*> us;
        while (head)
        {
            if (us.find(head->next) != us.end())
            {
                return true;
            }
            else 
            {
                us.insert(head);
                head = head->next;
            }
        }
        // 跳出循环证明已经遍历到nullptr了
        return false;
    }