-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.js
84 lines (75 loc) · 1.95 KB
/
LinkedList.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
75
76
77
78
79
80
81
82
83
84
export class LinkedList {
constructor() {
if (LinkedList.nodePool === undefined) {
LinkedList.nodePool = {
last: null,
count: 0
};
}
this.first = null;
this.last = null;
this.count = 0;
}
add(obj) {
var node = LinkedList.nodePool.last;
if (node === null) {
node = new LinkedListNode();
} else {
LinkedList.nodePool.last = node.prev;
LinkedList.nodePool.count--;
}
node.value = obj;
// if (obj === Object(obj)) {
// var funcDispose = obj.dispose;
// obj.dispose = function () {
// if (funcDispose) funcDispose();
// if (node.list === null) return;
// node.list.remove(node);
// }
// }
if (this.last) {
this.last.next = node;
}
node.prev = this.last;
this.last = node;
this.count++;
if (this.first === null) {
this.first = node;
}
node.list = this;
return node;
}
remove(node) {
if (node.next !== null) {
node.next.prev = node.prev;
}
if (node.prev !== null) {
node.prev.next = node.next;
}
if (this.last === node) {
this.last = node.prev;
}
if (this.first === node) {
this.first = node.next;
}
node.list = null;
node.value = null;
node.prev = LinkedList.nodePool.last;
LinkedList.nodePool.last = node;
LinkedList.nodePool.count++;
node.next = null;
this.count--;
}
}
export class LinkedListNode {
constructor() {
this.list = null;
this.value = null;
this.prev = null;
this.next = null;
}
dispose() {
if (this.list === null) return;
this.list.remove(this);
}
}