题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
思路挺简单,通过所以例子需要注意单个循环和左边可能出现空指针的问题
*/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
#include <iostream>
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* slow = pHead;
ListNode* fast = pHead;
do {
if (!slow->next || !slow ||!fast) {
cout << "null";
return nullptr;
}
if (slow->next->val == slow->val) {
return slow;
}
slow = slow->next;
if(fast->next->next){
fast=fast->next->next;
}else{
cout<<"null";
return nullptr;
}
if (fast->val == slow->val) {
break;
}
} while (fast->val != slow->val) ;
ListNode* begin = pHead;
while (begin->val != slow->val) {
begin = begin->next;
slow = slow->next;
}
return begin;
}
};