-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathLinked_List_Cycle.cpp
42 lines (42 loc) · 964 Bytes
/
Linked_List_Cycle.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
/**
* 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->next;
while(fast) {
fast = fast->next;
slow = slow->next;
if(fast) {
fast = fast->next;
if(fast == slow)
return true;
}
}
return false;
}
};
// with extra space
/*
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
unordered_map <ListNode*, bool> visited;
while(head) {
if(visited[head]) return true;
visited[head] = true;
head = head->next;
}
return false;
}
};
*/