55.链表中环的入口结点

题目描述

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

题目解答

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

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

    public ListNode EntryNodeOfLoop(ListNode pHead){
        if(pHead==null || pHead.next==null){
            return null;
        }

        ListNode pFast=pHead;
        ListNode pSlow=pHead;
        while(pFast!=null && pFast.next!=null) {
            pSlow = pSlow.next;
            pFast = pFast.next.next;
            if(pSlow==pFast){
                pFast=pHead;
                while(pFast!=pSlow){
                    pFast=pFast.next;
                    pSlow=pSlow.next;
                }
                if(pFast==pSlow){
                    return pSlow;
                }
            }
        }
        return null;
    }
}

快慢指针

 

posted @ 2019-01-15 14:42  chan_ai_chao  阅读(108)  评论(0编辑  收藏  举报