-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_142_LLCyle2.cpp
44 lines (36 loc) · 1007 Bytes
/
LC_142_LLCyle2.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
/*
* https://leetcode.com/problems/linked-list-cycle-ii/
* 142. Linked List Cycle II
*/
/**
* 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 empty LL or single node or two node
if(!head || !head->next || !head->next->next) return nullptr;
ListNode* slow = head->next, *fast = head->next->next;
while(slow && fast && fast->next)
{
if(slow == fast) break;
slow = slow->next;
fast = fast->next->next;
}
//if no cycle
if(slow != fast) return nullptr;
//if cycle exist, start from head node
slow = head;
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}// end
};