链表中环的入口节点

题目描述

  一个链表中包含环,请找出该链表的环的入口结点
  解法1:环的入口节点一定是入度为2的节点,故遍历链表,统计节点入度数,入度为2即为环入口节点
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        ListNode *res=NULL;
        set<ListNode*> nodeSet;
        nodeSet.insert(pHead);
        while(pHead)
        {
            std::pair<set<ListNode*>::iterator, bool> ret=nodeSet.insert(pHead->next);
            if(!ret.second)//节点指针插入失败表示已经存在,故为入口节点
            {
                res=*(ret.first);
                break;
            }
            pHead=pHead->next;
        }
        return res;
    }
};

  解法2:先求出环中节点数n,再两个指针一前一后,相隔为n,遍历链表,两个指针相遇点即为环的入口节点

 1 class Solution{
 2 public:
 3     int getLoopNum(ListNode* pHead)
 4     {
 5         ListNode *pre=pHead;
 6         ListNode *cur=pHead;
 7         while(cur)
 8         {
 9             cur=cur->next;
10             pre=pre->next;
11             if(cur)
12             {
13                 cur=cur->next;
14                 if(cur==pre)
15                 {
16                     int num=1;
17                     pre=pre->next;
18                     while(pre!=cur)
19                     {
20                         ++num;
21                         pre=pre->next;
22                     }
23                     return num;
24                 }
25             }
26             else return 0; 
27         }
28         return 0;
29     }
30     ListNode* EntryNodeOfLoop(ListNode* pHead)
31     {
32         int n=getLoopNum(pHead);//得到链表中环中节点个数,如果无环,返回0
33         if(n==0)return NULL;
34         else
35         {
36             ListNode *pre=pHead;
37             ListNode *cur=pHead;
38             while(n--)cur=cur->next;
39             while(pre!=cur)
40             {
41                 pre=pre->next;
42                 cur=cur->next;
43             }
44             return pre;
45         }
46     }
47 };

 

 

 

posted @ 2017-12-23 10:19  jeysin  阅读(204)  评论(0编辑  收藏  举报