-
Notifications
You must be signed in to change notification settings - Fork 692
/
CheckIfContainsCycle.java
87 lines (66 loc) · 2.13 KB
/
CheckIfContainsCycle.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
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
87
package linkedlist;
public class CheckIfContainsCycle {
public static boolean isCyclic(LinkedList linkedList) {
LinkedList.Node fast = linkedList.head();
LinkedList.Node slow = linkedList.head();
while (fast != null && fast.next() != null) {
fast = fast.next().next();
slow = slow.next();
if (fast == slow) {
return true;
}
}
return false;
}
private static class LinkedList {
private LinkedList.Node head;
private LinkedList.Node tail;
public LinkedList() {
head = new LinkedList.Node("head");
tail = head;
}
public void add(LinkedList.Node node) {
tail.setNext(node);
tail = node;
}
public void appendIntoTail(Node node) {
Node current = head;
while (current.next() != null) {
current = current.next();
}
current.setNext(node);
}
public LinkedList.Node head() {
return head;
}
public static class Node {
private LinkedList.Node next;
private String data;
public Node(String data) {
this.data = data;
}
public LinkedList.Node next() {
return next;
}
public void setNext(LinkedList.Node next) {
this.next = next;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
}
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.appendIntoTail(new LinkedList.Node("101"));
LinkedList.Node cycle = new LinkedList.Node("201");
linkedList.appendIntoTail(cycle);
linkedList.appendIntoTail(new LinkedList.Node("301"));
linkedList.appendIntoTail(new LinkedList.Node("401"));
linkedList.appendIntoTail(cycle);
System.out.println(isCyclic(linkedList));
}
}