剑指offer题解23:链表中环的入口结点

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

题解:

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

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

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        ListNode fast = pHead,slow = fast;
        if(pHead==null || pHead.next==null)
            return null;
        slow = slow.next;
        fast = fast.next.next;
        while(slow != fast){
            if(fast == null || fast.next==null)
                return null;
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode com = slow;
        int cnt=1;
        slow = slow.next;
        while(com!=slow){
            slow = slow.next;
            cnt++;
        }
        fast = pHead;
        while(fast!=com){
            fast = fast.next;
            com = com.next;
        }
        return com;
    }
}

你可能感兴趣的:(剑指offer)