-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_List _Cycle_Leetcode.cpp
61 lines (52 loc) · 1.21 KB
/
Linked_List _Cycle_Leetcode.cpp
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
54
55
56
57
58
59
60
#include<bits/stdc++.h>
using namespace std;
class ListNode{
public:
int data;
ListNode* next;
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
bool hasLoop = false;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
hasLoop = true;
break;
}
}
if(!hasLoop){
return nullptr;
}
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
// main function
int main(){
ListNode* head = new ListNode();
head->data = 1;
head->next = new ListNode();
head->next->data = 2;
head->next->next = new ListNode();
head->next->next->data = 3;
head->next->next->next = new ListNode();
head->next->next->next->data = 4;
head->next->next->next->next = head->next;
Solution ob;
ListNode* res = ob.detectCycle(head);
if(res){
cout<<"Loop found";
}else{
cout<<"No Loop";
}
return 0;
}