-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathJZ23.java
36 lines (33 loc) · 1004 Bytes
/
JZ23.java
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
// 23. 链表中环的入口结点
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ArrayList<Integer> list = new ArrayList<>();
while (pHead != null) {
if (list.contains(pHead.val)) {
return pHead;
}
list.add(pHead.val);
pHead = pHead.next;
}
return null;
}
public ListNode EntryNodeOfLoop2(ListNode pHead) {
if (pHead == null || pHead.next == null || pHead.next.next == null) {
return null;
}
ListNode node = pHead, slow = pHead.next, fast = pHead.next.next;
while (slow != fast) {
if (slow.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
} else {
return null;
}
}
while (node != slow) {
node = node.next;
slow = slow.next;
}
return slow;
}
}