-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathIsHaveCircle.java
56 lines (47 loc) · 1.18 KB
/
IsHaveCircle.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package algorithm;
public class IsHaveCircle {
static class Node {
Node next;
int value;
public Node(int value) {
this.value = value;
}
}
public static int isHaveCircleAndMeetWhere(Node head) {
if (head == null || head.next == null) {
return -1;
}
Node a = head;
Node b = head;
while (b.next.next != null) {
a = a.next;
b = b.next.next;
if (a == b) {
Node c = head;
while (c != a) {
a = a.next;
c = c.next;
}
return c.value;
}
a = a.next;
b = b.next.next;
}
return -1;
}
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n4;
System.out.println(isHaveCircleAndMeetWhere(n1));
}
}