-
Notifications
You must be signed in to change notification settings - Fork 257
/
linked-list-cycle-ii.cpp
73 lines (67 loc) · 1.91 KB
/
linked-list-cycle-ii.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* 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) {
auto slow = head, fast = head;
while (fast && fast->next) {
slow = slow->next, fast = fast->next->next;
if (slow == fast) { // There is a cycle.
slow = head;
// Both pointers advance at the same time.
while (slow != fast) {
slow = slow->next, fast = fast->next;
}
return slow; // slow is the begin of cycle.
}
}
return nullptr; // No cycle.
}
};
class Solution2 {
public:
ListNode *detectCycle(ListNode *head) {
auto slow = head, fast = head;
// Slow and fast pointer only meet when there is a cycle.
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
// Count length of the cycle.
int L = 0;
do {
slow = slow->next;
++L;
} while (slow != fast);
// Fast pointer walks L steps ahead.
fast = head;
while (L--) {
fast = fast->next;
}
// The start of the cycle is the node they meet.
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return nullptr;
}
};