题解 | #链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
// unordered_set<ListNode*> s;
// ListNode* cur_pHead=pHead;
// while(cur_pHead){
// if(s.find(cur_pHead)==s.end()){
// s.insert(cur_pHead);
// cur_pHead=cur_pHead->next;
// }else{
// return cur_pHead;
// }
// }
// return nullptr;
ListNode* fast=pHead,*slow=pHead;
while(fast && fast->next){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
break;
}
if(!fast || !fast->next)
return nullptr;
fast=pHead;
while(fast!=slow){
fast=fast->next;
slow=slow->next;
}
return fast;
}
};