-
Notifications
You must be signed in to change notification settings - Fork 1
/
141.cpp
43 lines (33 loc) · 837 Bytes
/
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
// 141. Linked List Cycle - https://leetcode.com/problems/linked-list-cycle
#include <bits/stdc++.h>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* next(ListNode *head) {
if (head == nullptr) {
return nullptr;
}
return head->next;
}
bool hasCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
do {
slow = next(slow);
fast = next(next(fast));
} while (slow != fast && fast != nullptr);
return fast != nullptr;
}
};
int main() {
ios::sync_with_stdio(false);
Solution solution;
assert(solution.hasCycle(nullptr) == false);
return 0;
}