File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-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
+ ListNode *detectCycle(ListNode *head) {
12
+
13
+ // edge case - empty list
14
+ if(!head || !head->next || !head->next->next)
15
+ {
16
+ return NULL ;
17
+ }
18
+
19
+ // check if linklist is cycle or not
20
+ ListNode* fast = head ;
21
+ ListNode* slow = head ;
22
+
23
+ while(fast != NULL && fast->next !=NULL)
24
+ {
25
+ fast = fast->next->next ;
26
+ slow = slow->next ;
27
+
28
+ if(slow == fast)
29
+ break ; // true ;
30
+ }
31
+
32
+ // exiting if we do not find a loop
33
+ if(slow != fast) return NULL ;
34
+
35
+ //or do this // if (!(fast && fast->next)) return NULL;
36
+
37
+
38
+
39
+ // finding the start of the loop
40
+ ListNode* slow2 = head ;
41
+ while(slow != slow2)
42
+ {
43
+ slow = slow->next ;
44
+ slow2 = slow2->next ;
45
+
46
+
47
+ }
48
+ return slow ;
49
+
50
+
51
+ }
52
+ };
53
+
54
+ //https://www.youtube.com/watch?v=Qq-vnKmzJR0
You can’t perform that action at this time.
0 commit comments