[141] 环形链表

70 阅读1分钟
/*
 * @lc app=leetcode.cn id=141 lang=javascript
 *
 * [141] 环形链表
 */

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