美文网首页
142. Linked List Cycle II

142. Linked List Cycle II

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

找到环形链表的第一个节点

  • 时间复杂度O(n),空间复杂度O(1)
  • Runtime: 88 ms, faster than 60.79%
  • Memory Usage: 41.5 MB, less than 69.61%

快慢指针,快指针到达节点后,慢指针指向头节点,然后一起走,相等的节点就是环形链表的第一个交点。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
  if (!head || !head.next) return null;
  let slow = head.next;
  let fast = head.next.next;
  while (slow !== fast) {
    if (!fast || !fast.next) return null;
    slow = slow.next;
    fast = fast.next.next;
  }
  slow = head;
  while (slow !== fast) {
    slow = slow.next;
    fast = fast.next;
  }
  return slow;
};

相关文章

网友评论

      本文标题:142. Linked List Cycle II

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