美文网首页
141. Linked List Cycle

141. Linked List Cycle

作者: jluemmmm | 来源:发表于2021-11-27 17:37 被阅读0次

    判断链表中是否有环。

    快慢指针。

    • 时间复杂度O(N),空间复杂度O(1)
    • Runtime: 88 ms, faster than 47.27%
    • Memory Usage: 41.5 MB, less than 29.33%
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    
    /**
     * @param {ListNode} head
     * @return {boolean}
     */
    var hasCycle = function(head) {
      if (!head || !head.next) return false;
      let slow = head;
      let fast = head.next;
      while (slow !== fast) {
        if (!fast || !fast.next) return false;
        slow = slow.next;
        fast = fast.next.next;
      }
      return true;
    };
    

    相关文章

      网友评论

          本文标题:141. Linked List Cycle

          本文链接:https://www.haomeiwen.com/subject/ulkqxrtx.html