/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode *>obj;///为了防止元素内容相同,这里选择存储整个链表的节点
while(head)
{
if(obj.count(head)==1)
{
return head;
}
obj.insert(head);
head=head->next;
}
return NULL;
}
};
LeetCode:142. 环形链表 II
本文介绍了一种使用集合存储链表节点来检测链表中是否存在循环的有效方法。通过遍历链表并检查节点是否已存在于集合中,可以快速定位到循环的起始节点。





