[剑指Offer] 55.链表中环的入口结点

题目描述

一个链表中包含环,请找出该链表的环的入口结点。

【思路】根据set集合的不重复,遍历链表时遇到的第一个重复结点就是环的入口结点。

 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     ListNode* EntryNodeOfLoop(ListNode* pHead)
13     {
14         if(pHead == NULL)
15             return NULL;
16         set<ListNode*> Set;
17         while(pHead){
18             if(!Set.insert(pHead).second)
19                 return pHead;
20             pHead = pHead->next;
21         }
22         return NULL;
23     }
24 };

 

posted @ 2017-03-17 09:50  Strawberry丶  阅读(130)  评论(0编辑  收藏  举报