-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhasCycle.cpp
More file actions
68 lines (61 loc) · 1.36 KB
/
hasCycle.cpp
File metadata and controls
68 lines (61 loc) · 1.36 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
Given a linked list, determine if it has a cycle in it.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//my Solution
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr)
return false;
ListNode* slow,*fast;
slow=head->next;
if(slow==nullptr)
return false;
else
fast=slow->next;
while(slow!=fast)
{
if(fast==nullptr)
return false;
slow=slow->next;
if(fast->next==nullptr)
return false;
else
fast=fast->next->next;
}
return true;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//better Solution
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL || head -> next == NULL)
return false;
ListNode *fast = head;
ListNode *slow = head;
while(fast -> next && fast -> next -> next){
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow)
return true;
}
return false;
}
};