环形链表:思路:如果head经过的节点之前已经遇到过了,说明就是环形链表,返回true。
先创建一个哈希表seen存储值
使用count方法:hash.count(key) // 该函数:用以统计key值在unordered_map中出现的次数。c++ unordered_map不允许有重复的key。因此,如果key存在,则count返回1,如果不存在,则count返回0
所以如果count(head)== 1的话就说明是环形链表,return true。
再把节点插入到哈希表中遍历下一个(必须,如果不插入的话会超时)
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> seen;
while (head != nullptr) {
if (seen.count(head)) {
return true;
}
seen.insert(head);
head = head->next;
}
return false;
}
};