-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay 21
43 lines (34 loc) · 1.12 KB
/
Day 21
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
Que: https://leetcode.com/problems/linked-list-cycle/
Case 1: Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Case 2: Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Case 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL) {
return false;
} else {
ListNode *slow = head, *fast = head->next;
while (slow != fast) {
if (fast == NULL || fast->next == NULL) {
return false;
} else {
slow = slow->next;
fast = fast->next->next;
}
}
return true;
}
}
};