-
Notifications
You must be signed in to change notification settings - Fork 0
/
142_linkedListCycle.cpp
executable file
·82 lines (68 loc) · 1.28 KB
/
142_linkedListCycle.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
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <set>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
static ListNode* hasCycle(ListNode *head) {
// set
// std::set<ListNode*> nodeSet;
// while (head) {
// auto ret = nodeSet.find(head);
// if (nodeSet.end() != ret) {
// return *ret;
// }
// nodeSet.insert(head);
// head = head->next;
// }
// return false;
// quick and slow pointer
ListNode *quick = head;
ListNode *slow = head;
ListNode *entry = NULL;
while (NULL != quick && NULL != quick->next) {
slow = slow->next;
quick = quick->next->next;
if (quick == slow) {
entry = head;
while (slow != entry) {
slow = slow->next;
entry = entry->next;
}
return entry;
}
}
return NULL;
}
};
void
showList(ListNode *head) {
while (head) {
std::cout << head->val << std::endl;
head = head->next;
}
}
int
main(int argc, char const *argv[])
{
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &b;
ListNode *ret = Solution::hasCycle(&a);
if (NULL != ret) {
std::cout << "begin at " << ret->val << std::endl;
}
else {
std::cout << "there is no cycle" << std::endl;
}
return 0;
}