注意
- 找到meet就跳出
- !的位置
- 双指针fast有可能在两个环节跳出
- 最后还需判断meet是否为空(==)
- 最后循环找到那个交点即可
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* slow = pHead;
ListNode* fast = pHead;
ListNode* meet = NULL;
if(!pHead){
return NULL;
}
while(fast){
slow = slow->next;
fast = fast->next;
if(!fast){
return NULL;
}
fast = fast->next;
if(fast == slow){
meet = fast;
break;
}
}
if(meet==NULL){
return NULL;
}
while(pHead&&meet){
if(pHead==meet){
return meet;
}
pHead= pHead->next;
meet = meet->next;
}
return NULL;
}
};
京公网安备 11010502036488号