-
Notifications
You must be signed in to change notification settings - Fork 0
/
queues.js
47 lines (44 loc) · 992 Bytes
/
queues.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
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
module.exports = class Queue {
constructor () {
this.first = null;
this.last = null;
this.size = 0;
}
enqueue(val) {
const newNode = new Node(val);
if(!this.first) {
this.head = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
this.size++;
return newNode;
}
dequeue() {
if(!this.first) return null;
var temp = this.first;
if(this.first === this.last) {
this.last = null;
}
this.first = this.first.next;
this.size--;
return temp.val;
}
print() {
var arr = [];
var current = this.head;
while(current) {
arr.push(current.val);
current = current.next;
}
console.log(arr);
}
}