LeetCode-初级-链表-环形链表(JavaScript)

给定一个链表,判断链表中是否有环。

进阶:
你能否不使用额外空间解决此题?


思路:

设置两个指针p1,p2。

p1每次走一步,p2每次走两步。

若没有环,则两者不会碰到,若有环,则必然会碰到。

/**
 * 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 || !head.next) return false
  let p1 = head,
      p2 = head.next;
  while (p2 && p2.next) {
    if (p1 === p2) return true;
    p1 = p1.next;
    p2 = p2.next.next;
  }
  return false;
};

猜你喜欢

转载自blog.csdn.net/romeo12334/article/details/82530610