-
Notifications
You must be signed in to change notification settings - Fork 0
/
141.cpp
53 lines (44 loc) · 1.13 KB
/
141.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
#include <map>
#include <iostream>
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 == nullptr)
return false;
map<ListNode*, bool> map;
ListNode* temp = head;
while (temp != nullptr) {
if (map[temp] == true)
return true;
map[temp] = true;
temp = temp->next;
}
return false;
}
};
/*I couldn't solve it with O(1) space complexity. Beside that, checked the solution. The solution has O(1) space complexity:
class Solution {
public:
bool hasCycle(ListNode* head) {
if (head == NULL || head->next == NULL) {
return false;
}
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != slow) {
if (fast->next == NULL || fast->next->next == NULL) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
*/