-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0142_detectCycle.cc
74 lines (65 loc) · 1.3 KB
/
Problem_0142_detectCycle.cc
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
74
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
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 || head->next->next == nullptr)
{
return nullptr;
}
ListNode *slow = head->next;
ListNode *fast = head->next->next;
while (slow != fast)
{
if (fast->next == nullptr || fast->next->next == nullptr)
{
return nullptr;
}
slow = slow->next;
fast = fast->next->next;
}
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
void testDetectCycle()
{
Solution s;
ListNode *x4 = new ListNode(-4);
ListNode *x3 = new ListNode(0);
ListNode *x2 = new ListNode(2);
ListNode *x1 = new ListNode(3);
x1->next = x2;
x2->next = x3;
x3->next = x4;
x4->next = x2;
ListNode *y2 = new ListNode(2);
ListNode *y1 = new ListNode(1);
y1->next = y2;
y2->next = y1;
ListNode *z = new ListNode(0);
EXPECT_TRUE(x2 == s.detectCycle(x1));
EXPECT_TRUE(y1 == s.detectCycle(y1));
EXPECT_TRUE(nullptr == s.detectCycle(z));
EXPECT_SUMMARY;
}
int main()
{
testDetectCycle();
return 0;
}