JS队列实现

队列即 FIFO 先进先出队列, 同样有着广泛的应用, 下面是相关的示例代码:

//队列的实现

function Queue(){

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
96
//队列的实现
function Queue(){
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.front = front;
this.back = back;
this.toString = toString;
this.empty = empty;
this.count = count;
}
function count(){
return this.dataStore.length;
}
function enqueue(element) {
this.dataStore.push(element);
}
function dequeue(){
return this.dataStore.shift();
}
function front() {
return this.dataStore[0];
}
function back() {
return this.dataStore[this.dataStore.length-1];
}
function toString(){
var retStr = "";
for (var i = 0; i < this.dataStore.length; i++){
retStr += this.dataStore[i] + "\n";
}
return retStr;
}
function empty() {
if( this.dataStore.length === 0){
return true;
}
else{
return false;
}
}
//模拟方块舞
//从txt文件中获取舞者
function Dancer(name,sex){
this.name = name;
this.sex = sex;
}
var fs = require('fs');
function getDancers(males, females) {
var names = fs.readFileSync("dancers.txt", "utf-8").split("\n");
for (var i = 0; i < names.length; ++i) {
names[i] = names[i].trim();
}
for (var i = 0; i < names.length; ++i) {
var dancer = names[i].split(" ");
var sex = dancer[0];
var name = dancer[1];
if (sex == "F") {
females.enqueue(new Dancer(name, sex));
}
else {
males.enqueue(new Dancer(name, sex));
}
}
}
//进行配对
function dance(males, females) {
console.log("The dance partners are: \n");
while(!females.empty() && !males.empty()) {
person = females.dequeue();
console.log("Female dancer is: " + person.name);
person = males.dequeue();
console.log(" and the male dancer is: " + person.name);
}
console.log(' ');
}
//方块舞测试程序
function dance_test(){
var maleDancers = new Queue();
var femaleDancers = new Queue();
getDancers(maleDancers, femaleDancers);
dance(maleDancers, femaleDancers);
if(!femaleDancers.empty()) {
console.log(femaleDancers.front().name + " is waiting to dance.");
}
if(!maleDancers.empty()){
console.log(maleDancers.front().name + " is waiting to dance.");
}
}

0%