-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked-list-cycle-ii.cpp
More file actions
51 lines (48 loc) · 1.25 KB
/
linked-list-cycle-ii.cpp
File metadata and controls
51 lines (48 loc) · 1.25 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
/**
* 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 || !head->next) return nullptr;
ListNode *s=head;
ListNode *f=head;
while(f && f->next){
s=s->next;
f=f->next->next;
if(s==f) break;
}
if(!f || !f->next) return nullptr;
s=head;
while(s!=f){
s=s->next;
f=f->next;
}
return f;
}
ListNode *detectCycle1(ListNode *head) {
if(!head || !head->next) return nullptr;
ListNode *s=head->next; //之前调试了很久,因为写成了"ListNode *s=head;"。注意 s的步长 和 f的步长 之间是二倍关系!!!
ListNode *f=head->next->next;
int n=0;
while(s!=f){
if(s->val==2) n++;
if(!f || !f->next || !f->next->next) return nullptr;
s=s->next;
f=f->next->next;
}
cout<<s->val<<" "<<n<<endl;
s=head;
while(s!=f){
s=s->next;
f=f->next;
}
return f;
}
};