考察知识点: 链表

题目分析:

 这道题和常见的使用快慢指针判断是否有环是不一样的。这道题中的链表中每一个指针都是独一无二的,所以快慢指针根本无法发挥作用。但是这道题测试用例太弱了,估计是像{3,2,0,-4,2,0,-4,2,0,-4,2,0,-4,2,0,-4,2,0,-4}这样手动{-4,2,0}循环的。

 实际上每过一个牛的编号就将他加入到集合中,保证他只出现一次就可以了。

所用编程语言: C++

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <unordered_map>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return bool布尔型
     */
    bool hasCycle(ListNode* head) {
        // write code here
        unordered_set<int> index;
        while (head) {
            if (index.count(head->val)) {
                return true;
            }
            index.insert(head->val);
            head = head->next;
        }
        return false;
    }
};