0%

142. 环形链表 II

142. 环形链表 II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ListNode* fast =head;
ListNode* slow=head;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
ListNode* index1=fast;
ListNode* index2=head;
while(index1!=index2){
index1=index1->next;
index2=index2->next;
}
return inedx2;
}
return NULL;
}
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
/**
* 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) {
ListNode *fast=head;
ListNode *slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;//走两部
slow=slow->next;//走一步
if(fast==slow){ //当快==慢时候(为什么不直返回slow呢?因为fast 不只走了一圈)
ListNode* index1=fast; //所以直接找它的地址再的地方
ListNode* index2=head; //从头数fast在哪
while(index1!=index2){
index1=index1->next;
index2=index2->next;
}
return index2;
}

}
return NULL;
}
};
-------------本文结束感谢您的阅读-------------
老板你好,讨口饭吃