-
Notifications
You must be signed in to change notification settings - Fork 0
/
No141_LinkedListCycle.cpp
55 lines (47 loc) · 1.12 KB
/
No141_LinkedListCycle.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
44
45
46
47
48
49
50
51
52
53
54
55
/*141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// directed method, use set to check if there is some duplicate
/*class Solution {
public:
bool hasCycle(ListNode *head) {
// for small data, set is better, because it doesn't need to cal the hash function
unordered_set<ListNode*> hashSet;
while(head){
if(hashSet.insert(head).second == false){
return true;
}
head = head->next;
}
return false;
}
};*/
//improvement, no need extra space
// fast and slow pointer, if there is a cycle, these two will ecounter with each other
class Solution{
public:
bool hasCycle(ListNode *head){
if(!head){
return false;
}
ListNode *fast = head;
ListNode *slow = head;
while(fast->next!=NULL && fast->next->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};