-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.js
67 lines (56 loc) · 1.27 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
function Queue() {
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.front = front;
this.back = back;
this.toString = toString;
this.empty = empty;
}
function enqueue(element) {
this.dataStore.push(element);
}
// function dequeue() {
// this.dataStore.shift();
// }
// 优先级队列,用code来标识优先级 越小优先级越高
function dequeue() {
var entry = 0;
for (var i = 0; i < this.dataStore.length; i ++) {
if (this.dataStore[i].code < this.dataStore[entry].code) {
entry = i;
}
}
return this.dataStore.splice(entry, 1);
}
function front() {
return this.dataStore[0];
}
function back() {
return this.dataStore[this.dataStore.length - 1];
}
// 优先级队列的toString也要改
function toString() {
var str = '';
for (var i = 0; i < this.dataStore.length; i ++) {
str += this.dataStore[i] + '\n';
}
return str;
}
function empty() {
if (this.dataStore.length === 0) {
return true;
}
return false;
}
// 优先级队列例子
function Patient(name, code) {
this.name = name;
this.code = code;
}
var p = new Patient('suhong', 5);
var ed = new Queue();
ed.enqueue(p);
p = new Patient('suhong1', 1);
ed.enqueue(p);
console.log(ed.dequeue()); // suhong1