【剑指Offer】链表中环的入口结点

题目

一个链表中包含环,如何找出环的入口结点?

实现

1
2
3
4
5
6
7
8
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public 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;
}