码迷,mamicode.com
首页 > 其他好文 > 详细

55、剑指offer--链表中环的入口结点

时间:2017-07-03 22:40:07      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:fast   turn   weight   lin   offer   lis   size   个数   bsp   

题目描述
一个链表中包含环,请找出该链表的环的入口结点。
 
解题思路:先通过快慢指针,找到环中结点,以确定环中结点个数,然后两个指针,一个先走环中结点个数步,然后两个指针一起走,直到相遇得为入口节点
 1 /*
 2 struct ListNode {
 3     int val;
 4     struct ListNode *next;
 5     ListNode(int x) :
 6         val(x), next(NULL) {
 7     }
 8 };
 9 */
10 class Solution {
11 public:
12     //通过快慢指针找到在环中的相遇点
13     ListNode* MeetingNode(ListNode *pHead)
14     {
15         //找到在环中的结点--快慢指针
16         if(pHead == NULL)
17             return NULL;
18         ListNode *slow = pHead;
19         ListNode *fast = pHead;
20         while(fast != NULL && fast->next != NULL)
21         {
22             slow = slow->next;
23             fast = fast->next->next;
24             if(fast == slow)//注意此处先移动,再判断
25                 return fast;
26         }
27         return NULL;
28     }
29     ListNode* EntryNodeOfLoop(ListNode* pHead)
30     {
31         ListNode *meetNode = MeetingNode(pHead);
32         if(meetNode == NULL)
33             return NULL;
34         int nodesInLoop = 1;
35         ListNode *pNode1 = meetNode;
36         while(pNode1->next != meetNode)
37         {
38             pNode1 = pNode1->next;
39             nodesInLoop++;
40         }
41         pNode1 = pHead;
42         for(int i=0;i<nodesInLoop;i++)
43         {
44             pNode1 = pNode1->next;    
45         }
46         ListNode *pNode2 = pHead;
47         while(pNode1 != pNode2)
48         {
49             pNode1 = pNode1->next;
50             pNode2 = pNode2->next;    
51         }
52         return pNode1;
53     }
54 };

 

55、剑指offer--链表中环的入口结点

标签:fast   turn   weight   lin   offer   lis   size   个数   bsp   

原文地址:http://www.cnblogs.com/qqky/p/7113015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!