Javascript Linked list cycle II Time limit exceeded ?


  • 0
    V
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    
    var detectCycle = function detectCycle(head) {
       
       if(!head || !head.next)
        return null;
       
       var node = checkNodes(head);
       
       if (node)
        return node;
       
       head = head.next;
       
       return detectCycle(head);
       
    },
    checkNodes = function checkNodes(head) {   
       var node = head;
       while(node && node.next && (node = node.next)) {
           var cycle = isCycle(head, node);
           if (cycle)
            return node;
           node = node.next;
       }
       return null;
    }, 
    isCycle = function isCycle(head, tail)  {
     
           if (head && tail.next) {
            var result = tail.next == head;
            return result;
           }
           return false;
    };

Log in to reply
 

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