-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetectCycle.cpp
44 lines (38 loc) · 968 Bytes
/
detectCycle.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
#include<iostream>
#include<unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *detectCycle(ListNode *head) {
if(!head || ! head->next){
return nullptr;
}
ListNode* fast = head->next, * slow = head, * equal = nullptr;
unordered_set<ListNode*> hash;
while(fast && fast->next){
if(fast == slow){
equal = fast;
break;
}else{
slow = slow->next;
fast = fast->next->next;
}
}
//无环
if(equal == nullptr){
return nullptr;
}
while(hash.insert(equal).second == true){
equal = equal->next;
}
while(hash.find(head) == hash.end()){
head = head->next;
}
return head;
}
int main(){
return 0;
}