-
Notifications
You must be signed in to change notification settings - Fork 0
/
141_linkedListCycle.cpp
executable file
·75 lines (61 loc) · 1.1 KB
/
141_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
#include <iostream>
#include <set>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
static bool hasCycle(ListNode *head) {
// set
// std::set<ListNode*> nodeSet;
// while (head) {
// if (nodeSet.end() != nodeSet.find(head)) {
// return true;
// }
// nodeSet.insert(head);
// head = head->next;
// }
// return false;
// quick and slow pointer
ListNode *quick = head;
ListNode *slow = head;
while (NULL != quick && NULL != quick->next) {
slow = slow->next;
quick = quick->next->next;
if (quick == slow) {
return true;
}
}
return false;
}
};
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 = &e;
// showList(&a);
if (Solution::hasCycle(&a)) {
std::cout << "hasCycle" << std::endl;
}
else {
std::cout << "has no cycle" << std::endl;
}
return 0;
}