forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution142.cpp
More file actions
73 lines (61 loc) · 1.48 KB
/
solution142.cpp
File metadata and controls
73 lines (61 loc) · 1.48 KB
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
/**
* Linked List Cycle II
* This question is based on math theroy describe as flollows:
* Suppose circumference is r, the whole linked list length is l, from beginning to cycle node is a and cycle node to encounter node is x, when fast and slow node meet, fast has run 2s, slow is s, then we have expression:
* 2s = s + n * r
* => s = n * r
* a + x = n * r
* r = l - a
* => a + x = (n - 1) * r + r
* => a = (n - 1) * r + r - x
* => a = (n - 1) * r + l - a - x
* Due to analysis, we have conclusion: if two pointer is from head and encounter and if they run by same speed, they will meet at cycle point.
*
* cpselvis ([email protected])
* August 29th, 2016
*/
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
bool hasCycle = false;
if (head == NULL || head -> next == NULL)
{
return NULL;
}
while (fast && fast -> next)
{
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow)
{
hasCycle = true;
break;
}
}
if (!hasCycle)
{
return NULL;
}
slow = head;
while (slow != fast)
{
slow = slow -> next;
fast = fast -> next;
}
return slow;
}
};
int main(int argc, char **argv)
{
Solution s;
//cout << s.detectCycle();
}