-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.js
95 lines (87 loc) · 2 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
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
/*
Authorship: Credit for the code in this file goes my tutor, Kirsten Brown.
I studied these algorithms on my own, and found the logic for each noted
below was what made most sense to me.
*/
/*
Queue
Average Worst
Access Search Insertion Deletion Access Search Insertion Delete
Time: Θ(n) Θ(n) Θ(1) Θ(1) O(n) O(n) O(1) O(1)
Space: O(n)
*/
class Node {
constructor() {
this.value = value
this.next = null;
}
}
class Queue {
constructor() {
this.first = null
this.last = null;
this.size = 0;
}
enqueue(value) { // add to end of list
let node = new Node(value);
if(!this.first) {
this.first = node;
this.last = node;
} else {
this.last.next = node
this.last = node;
}
this.size++
}
dequeue() { // return first from list
if(!this.first) return null
let temp = this.first;
if(this.first === this.last) {
this.last = null
}
this.first = this.first.next
this.size--
return temp.value;
}
}
class QElement {
constructor(data, priority) {
this.data = data;
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.array = []
}
enqueue(data, priority) {
const qElement = new QElement(data, priority)
let contains = false;
for(let i = 0; i < this.array.length; i++) {
if(this.array[i].priority > qElement.priority) {
this.array.splice(i, 0, qElement)
console.log('a[i]',this.array[i].priority)
contains = true;
break;
}
}
if(!contains) {
this.array.push(qElement)
}
}
dequeue() { // remove from end of beginning
if(this.array.length) {
return this.array.shift()
}
}
}
const priorityQueue = new PriorityQueue();
priorityQueue.enqueue("Neutron", 2234);
priorityQueue.enqueue("Quark", 1234);
priorityQueue.enqueue("Gluon", 2546);
priorityQueue.enqueue("Neutrino", 3432);
priorityQueue.enqueue("Electron", 2321);
priorityQueue.enqueue("Proton", 113);
priorityQueue.dequeue().data;
priorityQueue.dequeue().data;
console.log(priorityQueue.array);