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

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public static ListNode EntryNodeOfLoop(ListNode pHead)
    {
        ListNode meet = meetNode(pHead);
        
        if(meet == null){
            return null;
        }
        
        int repeatNode = 1;
        ListNode node = meet;
        while(node.next != meet){
            ++repeatNode;
            node = node.next;
        }
        node = pHead;
        //将快节点放在比头结点多环数个节点的位置
        for(int i = 0; i < repeatNode; i++){
            node = node.next;
        }
        ListNode node2 = pHead;
        while(node != node2){
            node = node.next;
            node2 = node2.next;
        }
        return node;
        
    }
    public static ListNode meetNode(ListNode pHead){
        
         if(pHead == null || pHead.next == null){
            return null;
        }
        ListNode pSlow = pHead.next;
        ListNode pFast = pSlow.next;
        
        while(pSlow != null && pFast !=null){
            if(pSlow == pFast){
                return pFast;
            }
            pSlow = pSlow.next;
            pFast = pFast.next;
            if(pFast != null){
                pFast = pFast.next;
            }
        }
        return null;
    }
}

 

posted @ 2019-05-31 10:07  紫色的雪  阅读(228)  评论(0编辑  收藏  举报