使用哈希表解决问题。

  1. 创建哈希表;
  2. 循环判断此时head是否为最后一个值;
  3. 判断head是否已经在哈希表内,若不在则将此时的head保存到哈希表中,并将head指向下一个值;
  4. 回到第2步,直到找到已存在于哈希表的head或者head为null.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /*---------------------------------*/
    // 创建哈希表
    /*---------------------------------*/
    unordered_set<ListNode*> visited;
    bool hasCycle(ListNode *head) {
        /*---------------------------------*/
        // 判断head是否为None
        /*---------------------------------*/
        while (head != nullptr)
        {
            /*---------------------------------*/
            // 检测此时的head值是否已经在哈希表内
            /*---------------------------------*/
            if (visited.count(head) != 0)
            {
                return true;
            }
            /*---------------------------------*/
            // 否则将head插入哈希表
            /*---------------------------------*/
            else
            {
                visited.insert(head);
            }
            head = head->next;
        }
        return false;
    }
};