-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path119LinkedListCycle.cpp
More file actions
51 lines (41 loc) · 974 Bytes
/
Copy path119LinkedListCycle.cpp
File metadata and controls
51 lines (41 loc) · 974 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == nullptr) return false;
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
return true;
}
}
return false;
}
};
int main() {
ListNode* n1 = new ListNode(3);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(0);
ListNode* n4 = new ListNode(-4);
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n2;
Solution obj;
bool result = obj.hasCycle(n1);
if(result)
cout << "Cycle Detected\n";
else
cout << "No Cycle\n";
return 0;
}