-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200212-2.cpp
66 lines (61 loc) · 1.3 KB
/
200212-2.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
// https://leetcode-cn.com/problems/linked-list-cycle/
// 进阶:使用常量内存(快慢指针法)
#include <cstdio>
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) return false;
ListNode* p = head;
ListNode* q = head->next;
while (p != q) {
p = (p ? p->next : NULL);
q = (q ? q->next : NULL); q = (q ? q->next : NULL);
}
return (p != NULL);
}
};
void release(ListNode* t)
{
unordered_set<ListNode*> s;
ListNode* p = t;
for (; p && s.find(p) == s.end(); p = p->next) {
s.insert(p);
}
for (auto e : s) delete e;
}
int main()
{
Solution s;
{
ListNode* n0 = new ListNode(3);
ListNode* n1 = new ListNode(2);
ListNode* n2 = new ListNode(0);
ListNode* n3 = new ListNode(-4);
n0->next = n1; n1->next = n2; n2->next = n3;
n3->next = n1; // pos = 1
printf("%d\n", s.hasCycle(n0)); // answer: true
release(n0);
}
{
ListNode* n0 = new ListNode(1);
ListNode* n1 = new ListNode(2);
n0->next = n1;
n1->next = n0; // pos = 0
printf("%d\n", s.hasCycle(n0)); // answer: true
release(n0);
}
{
ListNode* n0 = new ListNode(1);
; // pos = -1
printf("%d\n", s.hasCycle(n0)); // answer: false
release(n0);
}
return 0;
}