-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path142.cpp
29 lines (28 loc) · 820 Bytes
/
142.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL||head->next==NULL||head->next->next==NULL) return NULL;
ListNode *slow=head->next;
ListNode *fast=head->next->next;
while(slow!=fast){ //if slow pointer meets fast pointer, it means there exists a circle
if(slow->next==NULL) return NULL;
slow=slow->next;
if(fast->next==NULL||fast->next->next==NULL) return NULL;
fast=fast->next->next;
}
fast=head;
while(slow!=fast){
fast=fast->next;
slow=slow->next;
}
return fast;
}
};