-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_cycle.cpp
More file actions
53 lines (35 loc) · 1.37 KB
/
Linked_List_cycle.cpp
File metadata and controls
53 lines (35 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
EXPLANATION
Floyd’s Cycle-Finding Algorithm // fast slow approach // 2 pointers // "tortoise and the hare algorithm"
Approach: This is the fastest method and has been described below:
Traverse linked list using two pointers.
Move one pointer(slow_p) by one and another pointer(fast_p) by two.
If these pointers meet at the same node then there is a loop. If pointers do not meet then linked list doesn’t have a loop.
image
Above linked list has a loop as node 5 is connected to node 2 foming a Cycle.
CODE WITH EXPLANATION
Time Complexity : O(N)
Space Complexity : O(1)
class Solution {
public:
bool hasCycle(ListNode *head) {
// if head is NULL then return false;
if(head == NULL)
return false;
// making two pointers fast and slow and assignning them to head
ListNode *fast = head;
ListNode *slow = head;
// till fast and fast-> next not reaches NULL
// we will increment fast by 2 step and slow by 1 step
while(fast != NULL && fast ->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
// At the point if fast and slow are at same address
// this means linked list has a cycle in it.
if(fast == slow)
return true;
}
// if traversal reaches to NULL this means no cycle.
return false;
}
};