-
Notifications
You must be signed in to change notification settings - Fork 1
/
142.cpp
53 lines (41 loc) · 1.01 KB
/
142.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
// 142. Linked List Cycle II - https://leetcode.com/problems/linked-list-cycle-ii
#include <bits/stdc++.h>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* next(ListNode *head) {
if (head == nullptr) {
return nullptr;
}
return head->next;
}
ListNode* detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
do {
slow = next(slow);
fast = next(next(fast));
} while (slow != fast && fast != nullptr);
if (fast == nullptr) {
return nullptr;
}
slow = head;
while (slow != fast) {
slow = next(slow);
fast = next(fast);
}
return slow;
}
};
int main() {
ios::sync_with_stdio(false);
Solution solution;
assert(solution.detectCycle(nullptr) == false);
return 0;
}