Given a linked list, determine if it has a cycle in it.
这个就可以使用快慢指针了,快指针一次走两步,慢指针一次走一步,如果快指针直接就到最后一个节点了,那肯定是没有环,如果什么时候快指针又和慢指针重合了,那就是有环。
/**
* 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;
}
var slow = head;
var fast = head;
while (fast!==null) {
slow = slow.next;
fast = fast.next;
if (fast!==null) {
fast = fast.next;
}
if (slow===fast&&slow!==null) {
return true;
}
}
return false;
};