题目来源:
力扣
https://leetcode.cn/problems/linked-list-cycle/题目简介:
判断一个链表里包不包含环形链表,环形链表就是,结点的next往前指指到一个之前遍历过的结点上,如果这个链表包含环形链表就返回ture,如果不包含就返回false
思路:一样的用个哈希表,记录遍历过的结点的值和下标。遇到第二次出现的就false,遍历完没出现就返回ture
代码实现:
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set
while (head != nullptr) {
if (seen.count(head)) {
return true;
}
seen.insert(head);
head = head->next;
}
return false;
}
};