-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinked-List-Cycle.cpp
More file actions
30 lines (24 loc) · 819 Bytes
/
Linked-List-Cycle.cpp
File metadata and controls
30 lines (24 loc) · 819 Bytes
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
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;
}
};