方法一 双指针:
/**
* 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
}