142. Linked List Cycle II

2021-11-29  本文已影响0人  jluemmmm

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

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

/**
 * 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;
};
上一篇 下一篇

猜你喜欢

热点阅读