142环形链表II

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
/**
* 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 *cur1 = head ;//cur1 是快指针
ListNode *cur2 = head;//cur2 是慢指针
if(!head||!head->next)//如果头节点就是空,那就直接输出false
return NULL;
while(cur1&&cur1->next)
{

cur1 = cur1->next->next;
cur2 = cur2->next;
//相等的时候,我们进行快节点指向头部,慢节点不动,然后一起走的操作
if(cur1==cur2)
{
cur1 = head;
while(cur1!=cur2)
{
cur1= cur1->next;
cur2=cur2->next;
}
return cur2;
}
}
return NULL;
}
};
-------------本文结束,感谢您的阅读-------------