-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list_cycle.js
59 lines (49 loc) · 1.15 KB
/
linked_list_cycle.js
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
class Node {
data = null;
next = null;
constructor(data) {
this.data = data;
}
}
class LinkedList {
head = null;
add(node){
if(this.head === null) {
this.head = node;
return;
}
let nextNode = this.head;
while(nextNode.next){
nextNode = nextNode.next;
}
nextNode.next = node;
}
hasCycle() {
const nexts = new Set();
let nextNode = this.head;
while(nextNode.next){
if(nexts.has(nextNode)) { return true; }
nexts.add(nextNode);
nextNode = nextNode.next;
}
return false;
}
}
function main() {
const list = new LinkedList();
const array = [1,2,3,4,5,6];
array.forEach(a => {
list.add(new Node(a));
})
let node = list.head;
while(node.next){
console.log(node.data);
node = node.next;
}
console.log(node.data);
// Insert cycle.
console.log(`Assert: has cycle = false: ${list.hasCycle()}`);
list.head.next.next.next = list.head;
console.log(`Assert: has Cycle = true: ${list.hasCycle()}`);
}
main();