-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0141.linked-list-cycle.cpp
More file actions
57 lines (43 loc) · 1.19 KB
/
Copy path0141.linked-list-cycle.cpp
File metadata and controls
57 lines (43 loc) · 1.19 KB
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
// https://leetcode.com/problems/linked-list-cycle/
// this is an accepted submission but not optimal
// the optimal solution uses hare and tortoise approach
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
std::vector<ListNode*> tracker;
ListNode *current = head;
while (current != nullptr) {
auto it = std::find(tracker.begin(), tracker.end(), current);
if (it != tracker.end()) {
return true;
}
tracker.push_back(current);
current = current->next;
}
return false;
}
};
class Solution2 {
public:
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr) return false;
ListNode *slow = head;
ListNode *fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
if (slow == fast) {
return true;
}
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};