-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample24.java
61 lines (45 loc) · 1.38 KB
/
Example24.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
package applications.algorithms;
import datastructs.adt.SingleLinkedList;
import java.util.ArrayList;
import java.util.List;
/** Category: Algorithms
* ID: Example24
* Description: Detect a cycle in a single linked list
* Taken From: HackerRank Get Node Value
* Details:
* TODO
*/
public class Example24 {
public static boolean hasCycle(final SingleLinkedList<Integer> list){
List<SingleLinkedList<Integer>.Node> nodes = new ArrayList<>();
SingleLinkedList<Integer>.Node head = list.front();
while( head != null ){
if( nodes.contains(head)){
return true;
}
else{
nodes.add(head);
}
head = head.getNext();
}
return false;
}
public static void main(String[] args){
SingleLinkedList<Integer> list = new SingleLinkedList<>();
list.pushBack(0);
list.pushBack(1);
list.pushBack(2);
list.pushBack(2);
list.pushBack(2);
list.pushBack(3);
list.pushBack(4);
list.pushBack(5);
list.pushBack(5);
list.pushBack(6);
SingleLinkedList<Integer>.Node head = list.front();
SingleLinkedList<Integer>.Node tail = list.tail();
// create a cycle
tail.setNext(head);
System.out.println("List has cycle: "+Example24.hasCycle(list));
}
}