-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path142.cpp
More file actions
32 lines (32 loc) · 676 Bytes
/
142.cpp
File metadata and controls
32 lines (32 loc) · 676 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
// towpointer.cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *p1 = hasCycle(head), *p2 = head;
if (p1 == nullptr)
return nullptr;
while (p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
ListNode *hasCycle(ListNode *head) {
ListNode *fast = head, *slow = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
return fast;
}
return nullptr;
}
};