图解

image.png

javascript

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val) {
  4. * this.val = val;
  5. * this.next = null;
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {boolean}
  11. */
  12. var hasCycle = function (head) {
  13. /**
  14. * 哈希
  15. */
  16. var map = new Map();
  17. while(head){
  18. if(map.has(head)) return true
  19. map.set(head,head.val)
  20. head = head.next;
  21. }
  22. return false;
  23. /**
  24. * 快慢指针
  25. */
  26. var p1 = head,p2 = head;
  27. while(p2 && p2.next){
  28. p1 = p1.next;
  29. p2 = p2.next.next;
  30. if(p1 == p2) return true
  31. }
  32. return false;
  33. };

C++

  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. bool hasCycle(ListNode *head) {
  12. if(head == NULL) return false;
  13. ListNode *p = head,*q = head->next;
  14. while(q!=p && q && q->next){
  15. p = p->next;
  16. q = q->next->next;
  17. }
  18. return p == q;
  19. }
  20. };