-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path141_Linked List Cycle.cpp
More file actions
53 lines (46 loc) · 1.21 KB
/
141_Linked List Cycle.cpp
File metadata and controls
53 lines (46 loc) · 1.21 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
#include <iostream>
// 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) {
if (!head) return false;
ListNode *slow = head;
ListNode *fast = head;
do {
if (!fast->next || !fast->next->next) return false;
fast = fast->next->next;
slow = slow->next;
} while (slow != fast);
return true;
}
};
class Solution2 {
public:
bool hasCycle(ListNode *head) {
if (!head || !head->next) return false;
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
int main() {
ListNode* a = new ListNode(1);
ListNode* b = new ListNode(2);
ListNode* c = new ListNode(3);
ListNode* d = new ListNode(4);
ListNode* e = new ListNode(2);
a->next = b; b->next = c; c->next = d; d->next = e; e->next = a;
Solution s;
bool flag = s.hasCycle(a);
std::cout << flag;
return 0;
}