-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
57 lines (47 loc) · 1.04 KB
/
queue.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
// Linked List
const { ListNode: Node } = require('../linked-list/list-node');
function Queue() {
this.size = 0;
this.front = null;
this.rear = null;
}
// Enqueue - Add item to the end of the queue
// 5
// 5 - 6 (rear)
Queue.prototype.enqueue = function(val) {
const node = new Node(val);
if (this.size === 0) {
this.front = node;
this.rear = node;
} else {
this.rear.next = node;
this.rear = node;
}
this.size += 1;
return this.size;
}
// Dequeue - Remove item from the front
// 5 - 6
// 5
Queue.prototype.dequeue = function() {
if (this.size === 0) {
return null;
}
const temp = this.front;
this.front = this.front.next;
temp.next = null;
if (this.size === 1) {
this.rear = null;
}
this.size -= 1;
return temp;
}
// isEmpty
Queue.prototype.isEmpty = function() {
return this.size === 0;
}
// Peek - Return the front element
Queue.prototype.peek = function() {
return this.front ? this.front.value : null;
}
module.exports = Queue;