-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.js
More file actions
53 lines (51 loc) · 1.44 KB
/
PriorityQueue.js
File metadata and controls
53 lines (51 loc) · 1.44 KB
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
class PriorityQueue {
constructor() {
this.items = [];
}
// enqueue function to add element to the queue as per priority
enqueue(element) {
var contain = false;
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].priority > element.priority) {
// Once the correct location is found it is enqueued
this.items.splice(i, 0, element);
contain = true;
break;
}
}
if (!contain) {
this.items.push(element);
}
}
// dequeue method to remove element from the queue
dequeue() {
if (this.isEmpty()) {
return "Underflow";
}
return this.items.shift();
}
// returns the highest priority element highest. Means the most highest priority is 0
front() {
if (this.isEmpty())
return "No elements in Queue";
return this.items[0];
}
// returns the lowest priorty element of the queue
rear() {
if (this.isEmpty())
return "No elements in Queue";
return this.items[this.items.length - 1];
}
isEmpty() {
// return true if the queue is empty.
return this.items.length == 0;
}
deleteRear() {
this.items.pop();
}
refresh(node) {
let index = this.items.indexOf(node);
this.items.splice(index, 1);
this.enqueue(node);
}
}