forked from darpanjbora/Java-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloydCycleDetector.java
More file actions
84 lines (72 loc) · 1.94 KB
/
Copy pathFloydCycleDetector.java
File metadata and controls
84 lines (72 loc) · 1.94 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
package FloydsCycleDetection;
public class FloydCycleDetector {
private int position;
private int length;
private boolean cycle;
private Node head, tortoise, hare;
public void detect(Node head) {
this.head = head;
this.tortoise = this.hare = head;
this.cycle = detectCycle();
if (cycle) {
System.out.println("Found cycle.");
this.position = findPosition();
this.length = cycleLength();
} else {
System.out.println("No cycle.");
this.position = -1;
this.length = 0;
}
}
public boolean hasCycle() {
return cycle;
}
public int length() {
return length;
}
public int position() {
return position;
}
private boolean detectCycle() {
if (tortoise == null || tortoise.next == null) {
return false;
}
while (hare != null && hare.next != null) {
System.out.printf("(%d, %d),", tortoise.data, hare.data);
tortoise = tortoise.next;
hare = hare.next.next;
if (tortoise == hare) {
System.out.printf("turtle(%d) == hare(%d)%n",
tortoise.data, hare.data);
return true;
}
}
return false;
}
private int findPosition() {
int i = 1;
tortoise = head;
System.out.printf("(%d, %d),", tortoise.data, hare.data);
while (tortoise != hare) {
tortoise = tortoise.next;
hare = hare.next;
++i;
}
return i;
}
private int cycleLength() {
int i = 0;
do {
hare = hare.next;
++i;
} while (tortoise != hare);
return i;
}
private static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
}