forked from firstcoder55/code-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.js
More file actions
46 lines (35 loc) · 938 Bytes
/
Copy pathqueue.js
File metadata and controls
46 lines (35 loc) · 938 Bytes
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
var Queue = module.exports = function () {
this.head = null;
this.tail = null;
this.length = 0;
};
Queue.prototype.enqueue = function (value) {
var node = {
value: value,
next: null
};
// If there is currently no head node, set it to the current node.
if (!this.head) {
this.head = node;
}
// If we have a tail node already, set it's next property to be the current
// node.
if (this.tail) {
this.tail.next = node;
}
// Update the tail to be the next node.
this.tail = node;
return this.length += 1;
};
Queue.prototype.dequeue = function () {
if (!this.head) { return; }
var node = this.head;
// Update the head reference and remove the next node reference from the
// previous head.
this.head = node.next;
node.next = null;
// Remove the tail node if we have no more head node.
if (!this.head) { this.tail = null; }
this.length -= 1;
return node.value;
};