方法一:哈希表—将指针指向的节点,去哈希表中查找,若没有将节点放入哈希表中

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode(int x) : val(x), next(NULL) {}
    7. * };
    8. */
    9. class Solution {
    10. public:
    11. ListNode *detectCycle(ListNode *head) {
    12. ListNode *slow=head;
    13. ListNode *result=NULL;
    14. unordered_set<ListNode *>s;
    15. s.emplace(head);
    16. while(slow){
    17. slow=slow->next;
    18. if(s.count(slow)){
    19. result=slow;
    20. break;
    21. }
    22. s.emplace(slow);
    23. }
    24. return result;
    25. }
    26. };