Skip to content

Commit 6a1b375

Browse files
authored
Create 142. Linked List Cycle II
1 parent 2f31a81 commit 6a1b375

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Linked List/142. Linked List Cycle II

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

0 commit comments

Comments
 (0)