这题的思路并不复杂,遍历整个链表,当其中的某一个节点出现了两次后,则证明该链表中存在环。这里还是利用了C++的set,其唯一性可以帮助判断一个节点是否出现过。如若最终节点指向null,则说明该链表中不含有环。AC代码如下:
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> ans;
while(head != nullptr) {
if(ans.count(head)) {
return true;
}
ans.insert(head);
head = head->next;
}
return false;
}
};