-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0141_hasCycle.cc
73 lines (65 loc) · 1.33 KB
/
Problem_0141_hasCycle.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
#include <iostream>
#include "UnitTest.h"
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool hasCycle(ListNode *head) { return getFirstLoopNode(head) != nullptr; }
ListNode *getFirstLoopNode(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 (slow->next == nullptr || fast->next->next == nullptr)
{
return nullptr;
}
slow = slow->next;
fast = fast->next->next;
}
fast = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
void testHasCycle()
{
Solution s;
ListNode *x4 = new ListNode(-4);
ListNode *x3 = new ListNode(0);
ListNode *x2 = new ListNode(2);
ListNode *x1 = new ListNode(3);
x4->next = x2;
x1->next = x2;
x2->next = x3;
x3->next = x4;
ListNode *y2 = new ListNode(2);
ListNode *y1 = new ListNode(1);
y1->next = y2;
y2->next = y1;
ListNode *z = new ListNode(1);
EXPECT_TRUE(s.hasCycle(x1));
EXPECT_TRUE(s.hasCycle(y1));
EXPECT_FALSE(s.hasCycle(z));
EXPECT_SUMMARY;
}
int main()
{
testHasCycle();
return 0;
}