-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetectCycle.java
55 lines (46 loc) · 878 Bytes
/
DetectCycle.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
package ctci;
//https://www.hackerrank.com/challenges/ctci-linked-list-cycle
public class DetectCycle {
public static void main(String[] args) {
// TODO Auto-generated method stub
Node n5 = new Node(5);
Node n4 = new Node(4,n5);
Node n3 = new Node(3,n4);
Node n2 = new Node(2,n3);
Node n1 = new Node(1,n2);
n5.next = n2;
Node head = n1;
System.out.println(hasCycle(head));
}
static boolean hasCycle(Node head) {
Node slow = new Node();
Node fast = new Node();
if (head != null) {
slow = head;
fast = head;
} else {
return false;
}
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
class Node {
int data;
Node next;
Node(){
}
Node(int d){
data=d;
}
Node(int d,Node n){
data=d;
next=n;
}
}