-
Notifications
You must be signed in to change notification settings - Fork 1
/
023-链表中环的入口结点.cpp
59 lines (52 loc) · 1.23 KB
/
023-链表中环的入口结点.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead==nullptr)
return nullptr;
ListNode* meetingNode=FindMeetingNode(pHead);
if(meetingNode==nullptr)
return nullptr;
ListNode* p1=meetingNode->next;
int num=1;
while(p1!=meetingNode){
p1=p1->next;
num++;
}
ListNode* p2=pHead;
while(num>0){
p2=p2->next;
num--;
}
p1=pHead;
while(p1!=p2){
p1=p1->next;
p2=p2->next;
}
return p1;
}
ListNode* FindMeetingNode(ListNode* pHead){
if(pHead==nullptr||pHead->next==nullptr)
return nullptr;
ListNode* slow=pHead;
ListNode* fast=slow->next;
while(slow!=nullptr&&fast!=nullptr){
if(slow==fast)
return slow;
slow=slow->next;
fast=fast->next;
if(fast!=nullptr)
fast=fast->next;
}
return nullptr;
}
};