-
Notifications
You must be signed in to change notification settings - Fork 62
/
linked_list_cycle.cpp
43 lines (38 loc) · 953 Bytes
/
linked_list_cycle.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
// 检测链表是否有环
#include "unordered_set"
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
// 使用一个哈希表
bool hasCycle1(ListNode *head) {
unordered_set<ListNode*> s;
while (head) {
auto it = s.find(head);
if (it != s.end()) {
return true;
}
head = head->next;
}
return false;
}
// 快慢指针
bool hasCycle2(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
};