shaojinghong / Algorithms

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

环形链表求入环起点

shaojinghong opened this issue · comments

原题:https://leetcode-cn.com/problems/linked-list-cycle-ii/submissions/

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

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
  let fast = head;
  let slow = head;
  let hasCycle = false;

  while (fast !== null && fast.next !== null) {
    fast = fast.next.next;
    slow = slow.next;
    if (fast === slow) {
        hasCycle = true;
        break; // 跳出循环,记录快慢指针相遇点为fast
    }
  }

  if (hasCycle) {
    let flag = head;
    while (flag !== fast) {
      flag = flag.next;
      fast = fast.next;
    }
    return flag;
  } else {
    return null;
  }
};