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. if(!head || !head.next) return false
    14. let cur = head.next
    15. const map = new Map()
    16. while(cur) {
    17. if(map.has(cur)) {
    18. return true
    19. }
    20. map.set(cur)
    21. cur = cur.next
    22. }
    23. return false
    24. };
    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. if(!head || !head.next) return false
    14. let slow = head.next
    15. let fast = head.next.next
    16. while(slow) {
    17. if(fast === null || fast.next === null) return false
    18. slow = slow.next
    19. fast = fast.next.next
    20. if(slow === fast) return true
    21. }
    22. return false
    23. };