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