Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Tag
Linked List, Two Pointers
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Classic two pointers problem.
Fast pointer jumps two steps a time,
Slow pointer jumps one step a time.
If fast meets slow, there is a cycle there;
If fast meets null, reaches the end, there is no cycle there.
var hasCycle = function (head) {
var fast = head;
var slow = head;
while (fast !== null && fast.next !== null) {
fast = fast.next.next;
slow = slow.next;
if (fast === slow) {
return true;
}
}
return false;
};