Given a linked list, determine if it has a cycle in it.
Can you solve it without using extra space?
/**
* 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 || head.next === null) {
return false;
}
var tail1 = head.next;
var tail2 = head.next.next;
while (tail1 && tail2) {
if (tail1 === tail2) {
return true;
}
tail1 = tail1.next;
if (tail2.next) {
tail2 = tail2.next.next;
}
else {
return false;
}
}
return false;
};