-
Notifications
You must be signed in to change notification settings - Fork 0
/
hasCycle.cc
39 lines (39 loc) · 1.06 KB
/
hasCycle.cc
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
/**
* 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 *first = head;
ListNode *second = head;
while (second->next && second->next->next) {
first = first->next;
second = second->next->next;
if (first == second) return true;
}
return false;
}
//------------------------------------------//
bool hasCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (!head) return false;
ListNode *a = head;
ListNode *b = head->next;
while (a && b) {
if (a == b) return true;
a = a->next;
if (b->next)
b = b->next->next;
else
break;
}
return false;
}
};