-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloopDetection.js
74 lines (61 loc) · 1.25 KB
/
loopDetection.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Singly linked list
class LinkedList {
constructor() {
this.head = this.tail = null;
this.size = 0;
}
// add it to the end of list
append(value) {
const node = new Node(value);
if (!this.tail) {
this.tail = this.head = node;
} else {
let oldTail = this.tail;
this.tail = node;
oldTail.next = this.tail;
}
return node;
}
// add it to the start of list
prepend(value) {
const node = new Node(value);
if (!this.head) {
this.head = this.tail = node;
} else {
let oldHead = this.head;
this.head = node;
this.head.next = oldHead;
}
return node;
}
loopDetect() {
let curr = this.head;
let head = this.head;
while (curr != null) {
if (curr.next == head) {
return console.log(curr.next);
}
curr = curr.next;
}
}
show() {
let curr = this.head;
while (curr != null) {
console.log(curr.data);
curr = curr.next;
}
}
}
class Node {
constructor(value, next) {
this.data = value;
this.next = next || null;
}
}
let circular = new LinkedList();
for (let num of [0, 1, 2, 3, 4]) {
circular.prepend(num);
}
// adding loop
circular.tail.next = circular.head;
circular.loopDetect();