forked from carpeventus/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntryNodeOfLoop.java
More file actions
86 lines (77 loc) · 1.95 KB
/
Copy pathEntryNodeOfLoop.java
File metadata and controls
86 lines (77 loc) · 1.95 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package Chap3;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
/**
* 一个链表中包含环,请找出该链表的环的入口结点。
*/
public class EntryNodeOfLoop {
private class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
/**
* 双指针法
* @param pHead 链表头结点
* @return 环的入口结点
*/
public ListNode entryNodeOfLoop(ListNode pHead)
{
ListNode pFast = pHead;
ListNode pSlow = pHead;
while (pFast != null && pFast.next != null) {
pFast = pFast.next.next;
pSlow = pSlow.next;
// 运行到此说明有环
if (pFast == pSlow) {
pFast = pHead;
while (pFast != pSlow) {
pFast = pFast.next;
pSlow = pSlow.next;
}
// 在入口节点处相遇
return pSlow;
}
}
return null;
}
/**
* 利用Set不可添加重复元素的性质
*/
public ListNode entryNodeOfLoop_set(ListNode pHead) {
if (pHead == null) {
return null;
}
Set<ListNode> set = new HashSet<>();
ListNode cur = pHead;
while (cur != null) {
if (!set.add(cur)) {
return cur;
}
cur = cur.next;
}
return null;
}
/**
* Map,思路同Set
*/
public ListNode entryNodeOfLoop_map(ListNode pHead) {
if (pHead == null) {
return null;
}
Map<ListNode, Boolean> map = new HashMap<>();
ListNode cur = pHead;
while (cur != null) {
if (map.containsKey(cur)) {
return cur;
}
map.put(cur, true);
cur = cur.next;
}
return null;
}
}