-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0142_linked_list_cycle_ii.cc
100 lines (87 loc) · 2.27 KB
/
0142_linked_list_cycle_ii.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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* Author: Lanqing Ye
* Date: 2019-10-03
*/
/*
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Fun One
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL || head -> next == NULL)
return nullptr;
ListNode *fast = head;
ListNode *slow = head;
while(fast -> next && fast -> next -> next){
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow){
break;
}
}
if(!fast -> next || (fast -> next && !fast -> next -> next)){
return nullptr;
}
int num = 1;
fast = fast -> next;
while(fast != slow){
num ++;
fast = fast -> next;
}
fast = head;
slow = head;
for(int i = 0;i < num;i++){
fast = fast -> next;
}
while(slow != fast){
slow = slow -> next;
fast = fast -> next;
}
return fast;
}
};
// Fun Two
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL || head -> next == NULL)
return nullptr;
ListNode *fast = head;
ListNode *slow = head;
while(fast -> next && fast -> next -> next){
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow)
break;
}
if(!fast -> next || (fast -> next && !fast -> next -> next)){
return nullptr;
}
slow = head;
while(slow != fast){
slow = slow -> next;
fast = fast -> next;
}
return fast;
}
};