js:数据结构笔记4--队列

时间:2024-05-20 15:07:02

队列是一种特殊的列表,数据结构为FIFO;

定义:

function Queue() {
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.front = front;
this.back = back;
this.count = count;
this.toString = toString;
this.isEmpty = isEmpty;
}
function enqueue(elem) {
this.dataStore.push(elem);
}
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 count() {
return this.dataStore.length;
}
function isEmpty() {
if(this.dataStore.length === 0) {
return true;
} else {
return false;
}
}

例子:

舞伴分配: demo

基数排序:demo

优先队列:demo