-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloyd.java
More file actions
65 lines (60 loc) · 1.17 KB
/
Floyd.java
File metadata and controls
65 lines (60 loc) · 1.17 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
public class Floyd {
/**
* Floyd判圈算法(双指针)
* @param head
* @return
*/
public boolean hasCycle(ListNode head){
if(head == null || head.next == null)
return false;
ListNode slow = head;
ListNode fast = head;
do{
if(fast == null || fast.next == null) return false;
slow = slow.next;
fast = fast.next.next;
}while(slow != fast);
return true;
}
/**
* 如果存在环,则求出环长
* @param head
* @return
*/
public int countCycleLength(ListNode head) {
if(!hasCycle(head)){
return 0;
}
ListNode slow = head;
ListNode fast = head;
do{
slow = slow.next;
fast = fast.next.next;
}while(slow != fast);
int cycleLength = 0;
do{
slow = slow.next;
fast = fast.next.next;
cycleLength++;
}while(slow != fast);
return cycleLength;
}
//找到环的起始位置
public ListNode detectCycle(ListNode head) {
if(!hasCycle(head)){
return null;
}
ListNode slow = head;
ListNode fast = head;
do{
slow = slow.next;
fast = fast.next.next;
}while(slow != fast);
ListNode start = head;
while(slow != start){
slow = slow.next;
start = start.next;
}
return start;
}
}