方法一:哈希表—将指针指向的节点,去哈希表中查找,若没有将节点放入哈希表中
/*** 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) {ListNode *slow=head;ListNode *result=NULL;unordered_set<ListNode *>s;s.emplace(head);while(slow){slow=slow->next;if(s.count(slow)){result=slow;break;}s.emplace(slow);}return result;}};
