链表中环的入口结点

 

 1 class Solution {
 2 public:
 3     
 4     ListNode* EntryNodeOfLoop(ListNode* pHead)
 5     {
 6       ListNode *res=NULL;
 7         if(pHead==NULL)
 8             return res;
 9         ListNode *p1=pHead,*p2=pHead;
10         while(true)
11             {
12             p1=p1->next;
13             if(p2->next)
14                 p2=p2->next->next;
15             else return res;
16             if(p1==p2)
17                 {
18                 res=p1;
19                  break;
20             }
21         }
22         int len=1;
23         while(p1->next!=p2)
24             {
25             p1=p1->next;
26             len++;
27         }
28         res=pHead;
29         while(len--)
30             {
31             res=res->next;
32         }
33         p2=pHead;
34         while(res!=p2)
35             {
36             res=res->next;
37             p2=p2->next;
38         }
39         return res;
40     }
41 };

 

posted on 2016-05-03 10:29  RenewDo  阅读(152)  评论(0编辑  收藏  举报

导航