File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode(int x) : val(x), next(NULL) {}
7
+ * };
8
+ */
9
+ class Solution {
10
+ public:
11
+ bool hasCycle (ListNode *head)
12
+ {
13
+ // Using Floyd's Cycle-Finding Algorithm
14
+ // SEE https://www.geeksforgeeks.org/floyds-cycle-finding-algorithm/
15
+ auto slowPtr = head;
16
+ auto fastPtr = head;
17
+
18
+ while (slowPtr != nullptr &&
19
+ fastPtr != nullptr &&
20
+ fastPtr->next != nullptr ) // this extra check needed only for the fast pointer as it will move 2 nodes at a time
21
+ {
22
+ slowPtr = slowPtr->next ;
23
+ fastPtr = fastPtr->next ->next ;
24
+
25
+ if (slowPtr == fastPtr)
26
+ {
27
+ // slow pointer and fast pointer point to the same node
28
+ // this can only occur at this point if a cycle occured in the linked list
29
+ // cycle detected
30
+ return true ;
31
+ }
32
+ }
33
+
34
+ // reached end of linked list
35
+ // cycle not detected
36
+ return false ;
37
+ }
38
+ };
You can’t perform that action at this time.
0 commit comments