My simple solution in JS


  • 1
    S

    Here's a simple JS solution involving two pointers moving at different speeds and a try/catch block to handle null pointer exceptions (since a null pointer would mean the list has no cycles):

    var hasCycle = function(head) {
        if (head) {
            var p1 = head, p2 = head;
            while (p2) {
                try {
                    p1 = p1.next;
                    p2 = p2.next.next;
                } catch (e) {
                    return false;
                }
                if (p1 === p2) return true;
            }
        }
        return false;
    };

  • 1

    Nice idea to use exception handling. I like it better on the outside, though, so it doesn't clutter the actual solution. And it's maybe a little faster that way as well.

    var hasCycle = function(head) {
        try {
            slow = fast = head
            while (true) {
                slow = slow.next
                fast = fast.next.next
                if (slow === fast)
                    return true
            }
        } catch (e) {
            return false
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.