Revision 2·24 Sept
Linked List Cycle
tl;dr
Check whether or not a linked list contains a cycle. If a cycle exists, return TRUE. Otherwise, return FALSE. The cycle means that at least one node can be reached again by traversing the next pointer.
full write-up
Check whether or not a linked list contains a cycle. If a cycle exists, return TRUE. Otherwise, return FALSE. The cycle means that at least one node can be reached again by traversing the next pointer.
Constraints
Let n be the number of nodes in a linked list.
- 0 ≤
n≤ 500 - −10⁵ ≤
Node.data≤ 10⁵
Solution To find cycle in linked list we'll use slow and fast pointer. Fast pointer will travel two nodes at a time while slow pointer will run with one node at a time. if at any point they become equal there is cycle in loop
function detectCycle(head){
let slow= head;
let fast = head;
while(fast!=null && fast.next!=null){
slow= slow.next;
fast=fast.next.next;
if(slow===fast){
return true
}
}
return false;
}
Complexity
Time: O(N)
Space: O(1)