【剑指Offer】链表中环的入口结点 Posted on 2017-09-07 | In Algorithm , 剑指Offer 题目一个链表中包含环,如何找出环的入口结点? 实现12345678public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }} 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758public ListNode EntryNodeOfLoop(ListNode pHead) { ListNode node = meetingNode(pHead); if (node == null) return null; int count = countNodes(node); return findEntry(pHead, count);}private ListNode meetingNode(ListNode head) { if (head == null) return null; ListNode slow = head; ListNode fast = head.next; while (fast != null) { if (fast == slow) return slow; if (fast.next == null) return null; slow = slow.next; fast = fast.next.next; } return null;}private int countNodes(ListNode node) { ListNode current = node.next; int count = 1; while (current != node) { count++; current = current.next; } return count;}private ListNode findEntry(ListNode head, int count) { ListNode slow = head; ListNode fast = head; for (int i = 0; i < count; i++) fast = fast.next; while (fast != slow) { fast = fast.next; slow = slow.next; } return slow;}