leetcode 每日一题---判断是否存在环形链表

方法一 双指针:

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

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
  var p = [head,head];
  if(p[0] && p[1]){
    p = [p[0].next,p[1].next?p[1].next.next:null]
      if(p[0] && p[0] === p[1]) return true
    }            
  return false  
}


方法二 迭代:
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
  while(head){
    if(head.flag) return true;
    head.flag =true;
    head = head.next;
    }         
  return false  
}
 

  

posted @ 2020-10-09 11:02  海边吹吹风  阅读(82)  评论(0)    收藏  举报