-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlist-cycle.cpp
More file actions
37 lines (33 loc) · 767 Bytes
/
Copy pathlist-cycle.cpp
File metadata and controls
37 lines (33 loc) · 767 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Time - O(N), Space - O(1)
ListNode* Solution::detectCycle(ListNode* A) {
if(A == nullptr) {
return nullptr;
}
bool has_cycle = false;
ListNode *slow_p = A, *fast_p = A;
while(slow_p && fast_p && fast_p->next) {
slow_p = slow_p->next;
fast_p = fast_p->next->next;
if(slow_p == fast_p) {
has_cycle = true;
break;
}
}
if(!has_cycle) {
return nullptr;
}
slow_p = A;
while(slow_p != fast_p) {
slow_p = slow_p->next;
fast_p = fast_p->next;
}
return slow_p;
}