-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_Cycle_II.cpp
More file actions
38 lines (37 loc) · 968 Bytes
/
Linked_List_Cycle_II.cpp
File metadata and controls
38 lines (37 loc) · 968 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
38
# number : 142
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return nullptr;
ListNode *slow_ptr, *quick_ptr;
slow_ptr = quick_ptr = head;
bool isCycle = false;
while (quick_ptr != nullptr && quick_ptr->next != nullptr) {
slow_ptr = slow_ptr->next;
quick_ptr = quick_ptr->next->next;
if (slow_ptr == quick_ptr) {
isCycle = true;
break;
}
}
if (!isCycle)
return nullptr;
else {
ListNode *p = head;
while (p != slow_ptr) {
p = p->next;
slow_ptr = slow_ptr->next;
}
return p;
}
}
};