两个方法,一个快慢指针,一个把所有节点存起来。快慢指针会更省内存。 下面是最直观的把所有节点存起来的方法,如果想不到快慢指针至少也得想到这个。

 * 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) {
        while (head != nullptr)
        {
            if (visited.count(head) != 0)
            {
                return true;
            }
            else
            {
                visited.insert(head);
            }
            head = head->next;
        }
        return false;
    }
};