Description:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
My code:
/**
* 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) {
return false;
}
if(!head.next) {
return false;
}
let slow = head, fast = head.next;
while(fast) {
if(fast == slow) {
return true;
} else {
fast = fast.next;
if(!fast) {
return false;
} else {
fast = fast.next;
slow = slow.next;
}
}
}
return false;
};
Note: 两个指针,一个步长大,一个步长小,如果在某个时刻相等则表明有环。步长大的是分步进行的,在第一次next时还要判断是否为null,如果是就返回false,否则再两个指针next,不然可能会出现null不存在next的情况。