JS 队列
队列
队列的操作
- 入队,在队尾插入新元素
- 出对,在队头删除旧元素
- 读取,读取对头的元素 peeks
队列的抽象定义
- 入队 push
- 出对 shift
- 清空 clear
- 长度 length
- 显示 toString
- 队首 front
- 队尾 back
队列实现
function Queue() {
this.dataStore = []
this.enQueue = enQueue
this.deQueue = deQueue
this.front = front
this.back = back
this.clear = clear
this.toString = toString
this.isEmpty=isEmpty;
this.length=length;
}
function enQueue(element) {
this.dataStore.push(element);
}
function deQueue() {
return this.dataStore.shift();
}
function length() {
return this.dataStore.length;
}
function clear() {
this.dataStore = [];
}
function toString() {
return this.dataStore.map(function (item) {
return item;
}).join(',');
}
function front() {
return this.dataStore[0];
}
function back() {
this.dataStore[this.dataStore.length - 1];
}
function isEmpty() {
return this.dataStore.length <= 0;
}
1:队列的使用 方块舞模拟实现
function pairDancer(males,fmales){
document.write("舞者开始入场----");
document.write("<br />");
var num=1;
while(!males.isEmpty()&&!fmales.isEmpty()){
var male=males.deQueue();
console.log(male)
document.write("第"+num+"组入场的男性是:"+male.name);
document.write("<br />");
var fmale=fmales.deQueue();
document.write("第"+num+"组入场的女是:"+fmale.name);
document.write("<br />");
num++;
}
console.log("男性队列还有几人:"+males.length());
console.log("女队列还有几人:"+fmales.length());
}
2:队列的使用 队列排序(基数排序)基于 1-99的两位数字