链表中环的入口节点

题目:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

分析一:用HashSet解决

 1 public class Solution {
 2     public ListNode EntryNodeOfLoop(ListNode pHead)
 3     {
 4          if(pHead==null){return null;}
 5          HashSet<ListNode> set=new HashSet<ListNode>();
 6          while(pHead!=null){
 7              if(!set.add(pHead)){
 8                  return pHead;
 9              }
10              pHead=pHead.next;
11          }
12         return null;
13     }
14 }

 分析二:追击问题

 1 public class Solution {
 2     public ListNode EntryNodeOfLoop(ListNode pHead)
 3     {            
 4         if(pHead==null||pHead.next==null){return null;}
 5         ListNode fast=pHead;
 6         ListNode slow=pHead;
 7         while(true){
 8             if(fast==null||fast.next==null){return null;}
 9             slow=slow.next;
10             fast=fast.next.next;
11             if(fast==slow){break;}
12         }
13         
14         slow=pHead;
15         while(slow!=fast){
16             slow=slow.next;
17             fast=fast.next;
18         }
19         return slow;
20     }
21 }

 

posted @ 2019-05-06 11:19  JingMo  阅读(344)  评论(0)    收藏  举报