-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructures.js
145 lines (120 loc) · 3.17 KB
/
structures.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// TODO Type Checking
export class Node {
constructor(value, next = undefined) {
if (!(next === undefined || next.constructor.name === 'Node')) {
throw new TypeError('next must be undefined or node');
}
this.value = value;
this.next = next;
}
}
export class Heap {
// true is Min, false is Max
constructor(array = [], order = true) {
this.heap = array;
this._order = order;
this.build();
}
get val() {
return this.heap;
}
get order() {
return this._order;
}
set order(order = true) {
this._order = order;
this.build();
}
siftUp(i) {
let parent = Math.floor((i - 1) / 2);
if (parent > -1 && (this.heap[i] < this.heap[parent] == this._order)) {
[this.heap[i], this.heap[parent]] = [this.heap[parent], this.heap[i]];
return this.siftUp(parent);
}
return this.heap;
}
siftDown(i) {
let left = 2 * i + 1;
let right = left + 1;
let ext = -1;
if (this.heap[left] < this.heap[right] == this._order) {
ext = left;
} else {
ext = right;
}
if (right < this.heap.length && (this.heap[ext] < this.heap[i] == this._order)) {
[this.heap[i], this.heap[ext]] = [this.heap[ext], this.heap[i]];
return this.siftDown(ext);
}
return this.heap;
}
insert(x) {
this.heap.push(x);
this.siftUp(this.heap.length - 1);
return this.heap;
}
extract() {
let last = this.heap.length - 1;
[this.heap[0], this.heap[last]] = [this.heap[last], this.heap[0]];
let val = this.heap.pop();
this.siftDown(0);
return val;
}
// O(n) time complexity
build() {
let i = this.heap.length - 1;
while (i > -1) {
this.siftDown(i);
i --;
}
}
}
export class Queue {
constructor(node) {
if (node.constructor.name !== 'Node') {
throw new TypeError('must be node');
}
this.head = node;
this.size = 1;
while (node.next != undefined) {
node = node.next;
this.size ++;
}
this.tail = node;
}
enqueue(node) {
// enqueue(...Node)
if (node.constructor.name !== 'Node') {
throw new TypeError('must be node');
}
this.tail.next = node;
this.tail = node;
this.size ++;
return this;
}
dequeue() {
var node = this.head;
this.head = this.head.next;
this.size --;
return node.value;
}
join(queue) {
// join(...Queue)
if (queue.constructor.name !== 'Queue') {
throw new TypeError('must be queue');
}
this.tail.next = queue.head;
this.tail = queue.tail;
this.size += queue.size;
return this;
}
toArray() {
var array = [];
var pointer = this.head;
while (pointer != undefined) {
array.push(pointer.value);
pointer = pointer.next;
}
return array;
}
}