题解 | #链表中环的入口结点#
链表中环的入口结点
http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode* p=pHead; while(p) { ListNode *tmp=p->next; if(p==tmp) return p; p->next=p; p=tmp; } return NULL; } };
class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode* slow=pHead,*fast=slow; //使用快慢指针 if(slow==slow->next) return slow; if(!slow->next) return NULL; while(slow&&fast&&fast->next) { slow=slow->next; fast=fast->next->next; if(slow==fast) break; } if(fast==NULL) return NULL; ListNode* p=pHead; while(p!=slow) { p=p->next; slow=slow->next; } return p; } };