-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103.h
43 lines (41 loc) · 1.07 KB
/
103.h
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
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: The first node of linked list.
* @return: The node where the cycle begins. if there is no cycle, return null
*/
ListNode * detectCycle(ListNode * head) {
// write your code here
if(head == nullptr || head->next == nullptr)
return nullptr;
bool flag = false;
// 1判断是否有环
ListNode *fast = head, *slow = head;
while(fast != nullptr && fast->next != nullptr && !flag){
fast = fast->next->next;
slow = slow->next;
if(fast == slow) flag = true;
}
//cout << boolalpha << flag << endl;
// 没有环
if(!flag) return nullptr;
ListNode *start = head;
while(start != slow){
slow = slow->next;
start = start->next;
}
return start;
}
};