[142] 环形链表 II

80 阅读1分钟

思路:

1.先判断是不是环(环形链表I的解法基础上)

2.将快指针放到链表头,快慢指针都走一步,返回相遇的那一点

/*
 * @lc app=leetcode.cn id=142 lang=javascript
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * 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 === null) return null
  let slow = head,
    fast = head,
    isCycle = false
  while (fast.next !== null && fast.next.next !== null) {
    // 判断是不是慢指针下一步为空,快指针下两步是不是为空
    slow = slow.next
    fast = fast.next.next
    //如果有环就会一直转圈,快慢指针会重合在一起,重合就返回true
    if (slow === fast) {
      isCycle = true
      break
    }
  }
  if (!isCycle) return null
  // 将快指针放到链表头,快慢指针都走一步
  fast = head
  while (fast !== slow) {
    fast = fast.next
    slow = slow.next
  }
  return fast
}
// @lc code=end