-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked List Cycle.h
More file actions
46 lines (44 loc) · 1.13 KB
/
Linked List Cycle.h
File metadata and controls
46 lines (44 loc) · 1.13 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
/**
* 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) {
ListNode *slow = head;
ListNode *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
/*
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL)
return false;
ListNode *pos = head;
unordered_set<ListNode*> *hash = new unordered_set<ListNode*>();
while(pos != NULL && !findhash(pos, hash)) {
pos = pos->next;
}
if(pos == NULL)
return false;
else
return true;
}
bool findhash(ListNode *p, unordered_set<ListNode *> *hash) {
unordered_set<ListNode *>::const_iterator got = hash->find(p);
if(got == hash->end()) {
hash->insert(p);
return false;
}
return true;
}
*/
};